I'm new to JavaScript and i'm trying to create a login page and have the username and passwords or pins pull from an array. I tried my best to put it together and make it work, but I can't. Any help would be appertained. At the moment the login form is not pulling from the array. Please help.
original code:
}
var customer= ["John", "Mary", "Doe"]
var pin = [1452, 7858, 2016]
function validateusername(username) {
if (username == customer) {
return true;
}else {
return false;
}
}
function validatepassword(password) {
if (pin == pin) {
return true;
}else {
return false;
}
}
New updated code( still doesn't run)
<body>
<h1> Login to the Web ATM </h1>
<script src="js/scripts.js"></script>
<section class="loginform cf">
</section>
<form id="login" name="login" action="index_submit" onSubmit="return false" method="get" accept-charset="utf-8">
<table>
<tr>
<td> <label for="username">Username:</label></td>
<td><input type="text" name="username" id="username" placeholder="UserName" required ></td>
<td>REQUIRED</td>
</tr>
<tr>
<td><label for="password">PIN Number:</label></td>
<td><input type="password" name="password" id="password" placeholder="PIN" pattern="[0-9]{4}" required ></td>
<td>REQUIRED</td>
</tr>
<tr>
<td><label for="email">Email:</label></td>
<td><input type="email" name="email" id="email" placeholder="yourname#email.com" pattern="^(?=.*\..*)(?=.*#.*).*$" ><br/></td>
<td><div id="reqDisplay"></div></td>
</tr>
<tr>
<td> Empty </td>
<td><input id="emailBox" type="checkbox" name="checkbox" value="email transaction " onchange="displayReq()"/>email me a transaction confirmation</td>
<td> </td>
</tr>
<tr>
<td></td>
<td> Select an Account: <select>
<option value="account1">Checking</option>
<option value="account2">Savings</option>
<option value="account2">Money Market</option></select></td>
<td><input type="submit" value="Continue>>" onclick="validateForm()"></td>
</form>
</table>
<script type="text/javascript">
function displayReq(){
var divToReplace = document.getElementById("reqDisplay");
var chk = document.getElementById("emailBox");
var emailField = document.getElementById("email");
if (chk.checked) {
emailField.required = true;
divToReplace.innerHTML = "REQUIRED";
}else {
divToReplace.innerHTML = "";
emailField.required = false;
}
}
function validateForm(){
var myForm = document.getElementById("login");
var chk = document.getElementById("emailBox");
}
var all_usernames = ["John", "Mary", "Doe"];
var all_pins = ["1452", "7858", "2016"]; // Make it strings, since input values are strings
function validate_user(username, pin) {
var user_index = all_usernames.indexOf(username);
if (user_index > -1) {
return pin == all_pins[user_index];
} else {
return false;
}
function validateemail(email) {
if (email.indexOf("#") > -1 && email.indexOf(".") > -1) {
return true;
}else {
return false;
}
if (validateusername(myForm.username.value) && validatepassword(myForm.password.value) && (validateemail(myForm.email.value) || !chk.checked) ) {
alert("Welcome to your online ATM");
} else {
alert("Sorry the information you provided is incorrect");
}
}
</script>
You need to use different names for the global arrays and the function parameters. Otherwise, the parameter variables shadow the global variables, and you can't refer to the global variables inside the functions.
And the way to tell if something is in an array is with the indexOf() method, not ==.
var all_usernames = ["John", "Mary", "Doe"];
var all_pins = ["1452", "7858", "2016"]; // Make it strings, since input values are strings
function validate_username(username) {
return all_usernames.indexOf(username) > -1;
}
function validate_pin(pin) {
return all_pins.indexOf(pin) > -1;
}
Note that having separate functions to validate the username and PIN will not tell you if the user entered their correct PIN. For instance, if they enter username John, it won't check if they entered PIN 1452, it will allow 2016 or 7858 as well. You should use a single function to valdate both:
function validate_user(username, pin) {
var user_index = all_usernames.indexOf(username);
if (user_index > -1) {
return pin == all_pins[user_index];
} else {
return false;
}
}
Related
I created a registration page were users can sign up and I am trying to make a check that: email is valid, emails match, password meets length requirement, and passwords match. But it is not working properly. The html code is in the same form
Email Table Rows:
<tr>
<td></br>Email Address:</td>
</tr>
<tr>
<td><input id="em100" type="email" name="email1" required>
</td>
</tr>
<tr>
<td></br>Confirm Email Address:</td>
</tr>
<tr>
<td><input id="em101" type="email" name="email2" required></td>
</tr>
Password Table Rows:
<tr>
<td></br>Password:</td>
</tr>
<tr>
<td><input id="pw100" type="password" name="pass1" required></td>
</tr>
<tr>
<td></br>Confirm Password:</td>
</tr>
<tr>
<td><input id="pw101" type="password" name="pass2" required></td>
</tr>
Submit Table Rows:
<tr>
<td style="padding-top: 10px;"></br><input type="submit" value="Register" onclick="regValidation();"></td>
</tr>
Javascript Code:
function regValidation()
{
document.getElementById('td100').innerHTML = "";
event.preventDefault ? event.preventDefault() : event.returnValue = false;
var email1 = document.getElementById('em100').value;
var email2 = document.getElementById('em101').value;
var pass1 = document.getElementById('pw100').value;
var pass2 = document.getElementById('pw101').value;
if (document.getElementById('em100').checkValidity()) {
if (email1 = email2) {
if (pass1 = pass2) {
if (pass1.length >= #minPass || pass1.length <= #maxPass) {
return true && regSuccess();
} else {
document.getElementById('td100').innerHTML += "</br>Password must be #minPass - #maxPass characters.";
}
} else {
document.getElementById('td100').innerHTML += "</br>Passwords do not match.";
}
} else {
document.getElementById('td100').innerHTML += "</br>Emails do not match.";
}
} else {
document.getElementById('td100').innerHTML += "</br>Emails are not valid.";
}
}
function regSuccess()
{
alert("Thank you for signing up!");
document.getElementById('fm101').submit();
return;
}
You need to compare, and may chain the ifs a bit easier:
function getError(){
if(pass1 !== pass2) return "password missmatch";
if(email1 !== email2) return "emails missmatch";
if(pass1.length < min || pass1.length > max) return "password to long/short";
return false;
}
So you can do
var error = getError();
if(!error){
return alert(" all fine");
}
alert(error);
In your conditionals, you are assigning values:
if (pass1 = pass2)
This should probably be
if (pass1 == pass2)
1 Check your if statements
If(email1==email2)
{}
Samething for pass1 and pass2
If(pass1==pass2)
{}
2 If you put
<input type="email">
The browser will automatically do the email validation for you
3 to check that password does not exceed maximum length just add the
maxlength attribute to your input tag
<input type="password" maxlength="10">
Soo this saves you from writing additional js code
I am newbie in JavaScript. Can't find answer for this. I am not sure whether it is relevant.
I have a registration form with 2 fields.On submit, it should be validated. Here in my code, first written if condition only works. If the first if statement is commented, second if condition works.
HTML CODE :
<body>
<div align="center">
<h1>REGISTRATION</h1>
<form action="" method="post" name="reg">
<table>
<tr>
<td><label> Enter Full Name : </label></td>
<td><input type="text" id="id1" name="username" placeholder="minimum 6 charactors"></td>
</tr>
<tr><td></td><td><label style="color:red;" id="label1"></label></td></tr>
<tr>
<td><label> Gender : </label></td>
<td><input type="radio" name="gender" value="female"><label> Female </label>
<input type="radio" name="gender" value="male"><label> Male </label></td>
</tr>
<tr><td></td><td><label style="color:red;" id="label2"></label></td></tr>
</table>
<br/><button name="submit" value="submit" onclick="return validate_form()">Submit</button>
</form>
</div>
</body>
JS:
<script type="text/javascript">
function validate_form ()
{
var name=document.getElementById("id1").value;
var gender=document.getElementsByName("gender");
if(name=="")
{
document.getElementById("label1").innerHTML="Enter Name";
return false;
}
else if(name.length<6)
{
document.getElementById("label1").innerHTML="Minimum 6 charactors";
return false;
}
else
{
return true;
}
if(gender.checked)
{
return true;
}
else
{
document.getElementById("label2").innerHTML="Check gender";
return false;
}
}
</script>
In JSFiddle, it gives a error like
{"error": "Shell form does not validate{'html_initial_name': u'initial-js_lib', 'form': <mooshell.forms.ShellForm object at 0x56ae150>, 'html_name': 'js_lib', 'html_initial_id': u'initial-id_js_lib', 'label': u'Js lib', 'field': <django.forms.models.ModelChoiceField object at 0x56b3ed0>, 'help_text': '', 'name': 'js_lib'}{'html_initial_name': u'initial-js_wrap', 'form': <mooshell.forms.ShellForm object at 0x56ae150>, 'html_name': 'js_wrap', 'html_initial_id': u'initial-id_js_wrap', 'label': u'Js wrap', 'field': <django.forms.fields.TypedChoiceField object at 0x5c03510>, 'help_text': '', 'name': 'js_wrap'}"}
I donno what this error means!
You have to rewrite your validation code a bit.
Check demo - Demo:
Your problems:
function returns before gender is checked;
you cannot check multiple checkboxes this way: if(gender.checked)
Below is the working code
function validate_form() {
var name = document.getElementById("id1").value,
gender = document.getElementsByName("gender"),
result = true,
genderPass = 0;
if (name == "") {
document.getElementById("label1").innerHTML = "Enter Name";
result = false;
} else if (name.length < 6) {
document.getElementById("label1").innerHTML = "Minimum 6 charactors";
result = false;
} else {
document.getElementById("label1").innerHTML = "";
}
Array.prototype.forEach.call(gender, function(item) {
genderPass += item.checked ? 1 : 0
});
if (genderPass === 0) {
document.getElementById("label2").innerHTML = "Check gender";
result = false;
} else {
document.getElementById("label2").innerHTML = "";
}
return result;
}
function validate_form() {
var name = document.getElementById("id1").value,
gender = document.getElementsByName("gender"),
result = true,
genderPass = 0;
if (name == "") {
document.getElementById("label1").innerHTML = "Enter Name";
result = false;
} else if (name.length < 6) {
document.getElementById("label1").innerHTML = "Minimum 6 charactors";
result = false;
} else {
document.getElementById("label1").innerHTML = "";
}
Array.prototype.forEach.call(gender, function(item) {
genderPass += item.checked ? 1 : 0
});
if (genderPass === 0) {
document.getElementById("label2").innerHTML = "Check gender";
result = false;
} else {
document.getElementById("label2").innerHTML = "";
}
return result;
}
<div align="center">
<h1>REGISTRATION</h1>
<form action="" method="post" name="reg">
<table>
<tr>
<td><label> Enter Full Name : </label></td>
<td><input type="text" id="id1" name="username" placeholder="minimum 6 charactors"></td>
</tr>
<tr><td></td><td><label style="color:red;" id="label1"></label></td></tr>
<tr>
<td><label> Gender : </label></td>
<td><input type="radio" name="gender" value="female"><label> Female </label>
<input type="radio" name="gender" value="male"><label> Male </label></td>
</tr>
<tr><td></td><td><label style="color:red;" id="label2"></label></td></tr>
</table>
<br/><button name="submit" value="submit" onclick="return validate_form();">Submit</button>
</form>
</div>
When the function hits a return line, it leaves (ie returns from) the function and doesn't execute anything else in that function.
What people usually do is have a variable called valid or something similar that defaults to true. Then they have if statements that check only for things that would make the form invalid. If one of those if statements gets tripped, it handles the issue (eg telling the user that they need to fill in their gender) and sets valid to false. At the end, and only at the end, it returns valid. This way, if anything is making the form invalid, the function will return invalid, but nothing bad will happen if more than one if statement gets tripped because you can set valid to be false as many times as you want without causing any issues.
You can do it in this way.
<script type="text/javascript">
function validate_form ()
{
var name=document.getElementById("id1").value;
var gender=document.getElementsByName("gender");
var boolValidateName = validateName(name);
var boolValidateGnder = validateGnder(name);
if(boolValidateName && boolValidateGnder){
//if both are validate
}else{
//if either of or both not validate
}
}
var validateName = function (name){
if(name=="")
{
document.getElementById("label1").innerHTML="Enter Name";
return false;
}
else if(name.length<6)
{
document.getElementById("label1").innerHTML="Minimum 6 charactors";
return false;
}
else
{
return true;
}
}
var validateGender = function(gender){
if(gender.checked)
{
return true;
}
else
{
document.getElementById("label2").innerHTML="Check gender";
return false;
}
}
</script>
Your return statement is not placed very well.
You can break your business login into function and call it.So,every return statement get an equal chance to run.
getElementsByName will return nodelist. You will have to iterate it to get the checked value.
Also note, return ends the current function and returns execution flow to the calling function hence any line of code after execution of return will not be executed.
Do not forget to empty('') the error messages.
Try this:
function validate_form() {
var name = document.getElementById("id1").value;
var gender = document.getElementsByName("gender");
document.getElementById("label1").innerHTML = '';
document.getElementById("label2").innerHTML = '';
var genValue = '';
for (var i = 0; i < gender.length; i++) {
if (gender[i].checked) {
genValue = gender[i].value;
}
}
if (!name) {
document.getElementById("label1").innerHTML = "Enter Name";
return false;
} else if (name.length < 6) {
document.getElementById("label1").innerHTML = "Minimum 6 charactors";
return false;
} else if (!genValue) {
document.getElementById("label2").innerHTML = "Check gender";
return false;
}
return true;
}
<div align="center">
<h1>REGISTRATION</h1>
<form action="" method="post" name="reg">
<table>
<tr>
<td>
<label>Enter Full Name :</label>
</td>
<td>
<input type="text" id="id1" name="username" placeholder="minimum 6 charactors">
</td>
</tr>
<tr>
<td></td>
<td>
<label style="color:red;" id="label1"></label>
</td>
</tr>
<tr>
<td>
<label>Gender :</label>
</td>
<td>
<input type="radio" name="gender" value="female">
<label>Female</label>
<input type="radio" name="gender" value="male">
<label>Male</label>
</td>
</tr>
<tr>
<td></td>
<td>
<label style="color:red;" id="label2"></label>
</td>
</tr>
</table>
<br/>
<button name="submit" value="submit" onclick="return validate_form()">Submit</button>
</form>
</div>
Fiddle here
When your first block of if..else statements returns, it returns for the whole function and the if for gender never even runs. remove:
else
{
return true;
}
I am validating a form which has validations for required field, character, number, email, password format, length of a field.
In my code, required field and length are working but the rest.
JavaScript code for Password format:
function CheckPassword(paswd) {
var submitFlag = false;
var paswd = /^(?=.*[0-9])(?=.*[!##$%^&*_])[a-zA-Z0-9!##$%^&*]{7,15}$/;
if (document.reg_indi_form.pswd.length > 0) {
if (!document.reg_indi_form.pswd.value.match(paswd)) {
submitFlag = true;
document.getElementById('i3').innerHTML = "Use atleast one digit,character,specialCharacter";
document.getElementById('i3').style.color = "red";
document.getElementById('i10').style.fontSize = "12px";
//return false;
}
}
return submitFlag;
}
function alls() {
var valid = true;
valid *= req();
valid *= validateUname();
valid *= CheckPassword(this);
valid *= num();
valid *= confirm_pswd();
valid *= namevalid();
valid *= ValidateEmail(this);
return valid ? true : false;
}
I am calling alls() on onSubmit.
All other functions which are not working are similar to checkPassword().
HTML code:
<form name="reg_indi_form" method="post" onSubmit="return alls()" enctype="multipart/form-data" >
<table height="100" width="1000">
<tr>
<td>
First Name<font color="#FF0000">*</font>:
</td>
<td>
<input name="txt_fnm" type="text" id="txt_fnm"/> <label id="i"></label>
</td>
</tr>
<tr>
<td>
Password<font color="#FF0000">*</font>:
</td>
<td>
<input type="password" name="pswd" id="pswd"/><label id="i3"></label>
</td>
</tr>
<tr>
<td>
<input type="submit" name="submit" value="Submit"/>
</td>
<td>
<input type="reset" name="reset" value="Reset"/>
</td>
</tr>
</table>
</form>
Considering that your CheckPassword() returns true when the password is correct.
Now in your CheckPassword() function, document.reg_indi_form.pswd.value.match(paswd) this statement returns true if the pattern matches. You have added ! means it will return true when password doesn't matches to the given pattern. I have edited the function below, also consider using boolean operators instead of using multiple/nested if statements where ever possible. You don't have any field with id i10 I think it should be i3 instead.
function CheckPassword() {
var submitFlag = false;
var paswd = /^(?=.*[0-9])(?=.*[!##$%^&*_])[a-zA-Z0-9!##$%^&*]{7,15}$/;
if ((document.reg_indi_form.pswd.length > 0) && (document.reg_indi_form.pswd.value.match(paswd))) {
submitFlag = true;
}
else{
document.getElementById('i3').innerHTML = "Use atleast one digit,character,specialCharacter";
document.getElementById('i3').style.color = "red";
document.getElementById('i3').style.fontSize = "12px";
}
return submitFlag;
}
And finally why are you using *= operator for boolean values in your alls() function? You should use boolean operator. Also this passes the current form or field object to the function, it is not required in this context since you are using document.formName.fieldName to access the fields of the form. Also the ternary (bool?value1:value2) operator at the end is unnecessary.
function alls() {
var valid = req()
&& validateUname()
&& CheckPassword()
&& num()
&& confirm_pswd()
&& namevalid()
&& ValidateEmail();
return valid;
}
I have totally 6 textboxes here and i have applied different validations for them but none of them are working. here is my code can someone help me out where i have gone wrong.
Each textbox have different condition
1)it should accept only alphabets
2)it should accept only numbers
3)it should accept only email
4)it should accept only alphabets if u enter anything other then alphabet and press submit button background color of that particular textbox will change
<!DOCTYPE>
<html>
<head>
<title> Text Boxes </title>
<script>
function test(){
if(form.alphabets.value == "") {
alert('Please enter name');
return false;
} else {
if (!form.alphabets.value.match(/^[a-zA-Z]+$/)) {
alert("Please Enter only alphabets");
return false;
}
}
if(form.numbers.value == "") {
alert('Please enter phone number ');
return false;
} else {
if (!form.numbers.value.match(/^[0-9]+$/)) {
form.numbers.value="";
form.numbers.focus();
alert("Please Enter only numbers");
return false;
}
}
if(form.email.value == "") {
alert('Please enter email ');
return false;
} else {
if (!form.email.value.match(/^[a-zA-Z0-9_.+-]+#[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$/) ) {
form.email.value="";
alert("Please Enter Valid email address");
form.email.focus();
return false;
}
}
if(form.alphabets1.value == "") {
alert('Please don't enter numbers ');
return false;
} else {
if (!form.alphabets1.value.match(/^[a-zA-Z]+$/)) {
form.alphabets1.value="";
form.alphabets1.focus();
form.alphabets1.style.background="Red";
alert("Please Enter only alphabets");
return false;
}
}
function check()
{
var text = document.getElementById("txtarea_content").value;
if(text.length >= 4)
{
alert('Length should not be greater than 4');
return false;
}
else
{
return true;
}
}
function sum()
{
var txtFirstNumberValue = document.getElementById('txt1').value;
var txtSecondNumberValue = document.getElementById('txt2').value;
if (txtFirstNumberValue == "")
txtFirstNumberValue = 0;
if (txtSecondNumberValue == "")
txtSecondNumberValue = 0;
var result = parseInt(txtFirstNumberValue) + parseInt(txtSecondNumberValue);
document.getElementById('txt3').value = result;
}
</script>
</head>
<body>
<form name="form" method ="post">
<table>
<tr>
<td>Enter only Alphabets :</td>
<td><input type="text" name="alphabets" /></td>
</tr>
<tr>
<td>Enter only Numbers :</td>
<td><input type="text" name="numbers" /></td>
</tr>
<tr>
<td>Enter your Email Address : </td>
<td><input type="text" name="email"> </td>
</tr>
<tr>
<td>Enter only alphabets</td>
<td><input type="text" name="alphabets1"</td>
</tr>
<td> </td>
</table>
<button onclick="test();"> click me </button>
<td><br></td>
<td></br></td>
<div>
Enter only 4 values : <input type="text" length="3" id="txtarea_content" onkeypress="return check();"> </textarea>
</div>
<tr>
<td>Enter Two Numbers : <input type="text" id="txt1" onkeyup="sum();" />
<input type="text" id="txt2" onkeyup="sum();" />
</td>
<td> Result :<input type="text" id="txt3" /></td>
</tr>
</form>
</body>
</html>
You copy code error you function test() mistake } and alert('Please don't enter numbers ') error ' in don't .Please correct the code!
Hope this help!
why not try to get their id instead..here is the code
var alpa = document.getElementById('alphabets');
if(alpa.value == "") {
alert('Please enter name');
return;
} else {
if (!alpa.value.match(/^[a-zA-Z]+$/)) {
alert("Please Enter only alphabets");
return;
}
}
hope this'll help
The problem is here. Single quote(') ends unnecessary in the middle. Use double quotes(") in that place.
Instead of this
if(form.alphabets1.value == "") {
alert('Please don't enter numbers ');
return false;
}
Use this
if(form.alphabets1.value == "") {
alert("Please don't enter numbers ");
return false;
}
As tuan huynh said, you forgot to close the function test statement with }. In addition, have you think that some people would end up entering spaces in the name - because they have two names, for example? This regexp would accept those spaces (keep in mind that \w is the same than a-zA-Z ):
/^[\w|\s]+$/
People may even want to put accents on vowels or similar symbols in their names, and they won't match with a regexp that only looks for alphabets. This would make it, at least, for accents:
/^[\w|\s|á-úÁ-Ú|à-ùÀ-Ù]+$/
I hope this helps.
I'm currently doing javascript validation and everything's working perfectly except my age validation. If the person enters a value of type string it must give an alert for the user to enter his/her age as a numeric value...
I'm not quite sure how to go about this so your help will be very much appreciated!
You will see what I'm trying to do in the validAge function in the if-statement: line 55
Here is my code I have so far!
<!DOCTYPE HTML>
<html>
<head>
<title>Question 1 / Vraag 1 - Basic JavaScript Validaton / Basiese JavaScript validasie
</title>
<link rel="Stylesheet" type="text/css" href="style.css" />
<script language="javascript">
function validate()
{
var firstname = document.getElementById("firstname");
var surname = document.getElementById("surname");
var age = document.getElementById("age");
var email = document.getElementById("email");
if(notEmpty(firstname, "ENTER USERNAME"))
{
if(notEmpty(surname, "ENTER SURNAME"))
{
if(notEmpty(age, "ENTER AGE"))
{
if(validAge(age, "AGE MUST BE A NUMERIC VALUE"))
{
if(notEmpty(email, "ENTER EMAIL"))
{
if(emailValid(email, "ENTER A PROPER EMAIL ADDRESS"))
{
return emailValid();
}
}
}
}
}
}
return false;
}
function notEmpty(elem, helperMsg)
{
if(elem.value.length == 0)
{
alert(helperMsg);
elem.focus();
return false;
}
return true;
}
function validAge(elem, helperMsg)
{
var age = elem.value;
if(age <= 0 || age > 100 || age.type == string???))
{
alert(helperMsg);
return false;
}
return true;
}
function emailValid(elem, helperMsg)
{
var atpos = elem.value.indexOf("#");
var dotpos = elem.value.lastIndexOf(".");
if(atpos < 0 || dotpos < 0)
{
alert(helperMsg);
return false;
}
return true;
}
</script>
</head>
<body>
<form method="get" action="">
<table>
<tr>
<td> Firstname:</td>
<td> <input type="text" name="firstname" id="firstname" /><span id="fnError">
</span></td>
</tr>
<tr>
<td> Surname:</td>
<td> <input type="text" name="surname" id="surname"/><span id="snError">
</span></td>
</tr>
<tr>
<td> Age:</td>
<td> <input type="text" name="age" id="age"/><span id="aError">
</span></td>
</tr>
<tr>
<td> Email:</td>
<td><input type="text" name="email" id="email"/><span id="eError">
</span></td>
</tr>
<tr><td colspan="2"><input type="button" value="Validate" onClick="validate()" /></td></tr>
</table>
</form>
</body>
</html>
Use a RegExp to check whether it's a valid age. Methods such as isNaN will still allow floating-point numbers, though I have never heard anyone saying My age is twelve dot three.:
function validAge(elem, helperMsg)
{
var age = elem.value;
//Two digits, so anything between and including 0 and 99
if(/^\d{1,2}$/,test(age))
{
alert(helperMsg);
return false;
}
return true;
}
Another tip: Instead of nesting hundreds of if-conditions, you can also use the logical && (AND) operator.
if(a){
if(b){
if(c){
...
can be shortened to:
if(a && B && c){
You can use the isNan function!
I think this is what you want:
if(isNaN(age) || age <= 0 || age > 100))
The isNaN(age) uses the isNaN[MDN] function to check whether or not age is actually a number.
Note that this will allow floating point ages, which may or may not be what you want. If you prefer, you can only allow integer ages with this condition:
age % 1 === 0
Also, I would avoid nesting all the if statements. You could do a return after each one, like this:
if(notEmpty(firstname, "ENTER USERNAME")) return false;
if(notEmpty(surname, "ENTER SURNAME")) return false;
if(notEmpty(age, "ENTER AGE")) return false;
/// skip a few ...
return emailValid();
BTW, there are some people who are over 100 years old. This app would be bad for their user experience.
Try this using isNaN():
function validAge(elem, helperMsg)
{
var age = elem.value;
// If age is Not a Number, not at least 1, greater than 100, or has a decimal place.
if(isNaN(age) || age <= 0 || age > 100 || age.indexOf(".") >= 0)
{
alert(helperMsg);
return false;
}
return true;
}
All the above answers are correct.. If you think of re-usability please have a look at this plugin. It validates a form with small effort..
<html>
<head>
<title>Name</title>
<script>
function validatetext()
{
if(document.sign.fname.value=="")
{
alert("Missing First name!");
}
if(isNaN(document.sign.age())
{
alert("Enter numaric");
}
}
</script>
</head>
<body><form method=post name="sign">
<b>name:</b>
<input name="fname" type="text" size="30" maxlength="30" />
<br>
<b>age:</b>
<input name="age" type="text" size="30" maxlength="30" />
<input type="submit" name="signup" value="sign up" onclick="validatetext();" />
</form>
</body>
</html>