Hey guys, trying to teach myself a bit of javascript as i would like to get a website up and running. Please have a look at the code below. I'm trying to create input for a webpage. In the first piece of code, i'm declaring all the functions(which i'm sure are wrong) and i'm also attempting to validate them

The 2nd piece of code contains the area where i'm calling them. As you can probably see, the code is a bit rough. Most of the info i've pieced together from reading previous answers on this forum.

I realise there are probably many errors here but if someone can start me in the right direction with whats wrong, i'd be happy with that.

Thanks in advance.

/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

function validateAll(myForm){

    validateNoOfDigits1(myForm.Firstname);
    validateNoOfDigits1(myForm.Surname);
    validateNoOfDigits2(myForm.Age);
    validateAge(myForm.Age);
    validateNotEmpty(myForm.Username);
    validatePassword(myForm.pass1);
    validateNoOfDigits3(myForm.pass1);
    validatePasswordEqual(myForm.pass2);
    validateNoOfDigits3(myForm.pass2);

}


function validateNotEmpty(value){
if (value==null || value==""){
alert("Field cannot be empty");
return false;
}
return true;
}


function validateAge(value){
checkvalue=parseFloat(value);
if (value<18){
var txt = "Applicants must be over 18";
alert(txt);
return false;
}
return true;
}

function validateNoOfDigits1(value){
if (value.length<=1){
alert("Incorrect input. Please enter name correctly.");
return false;
}
return true;
}


function validateNoOfDigits2(value){
checkvalue=parseInt(value);
if (value.length<=0 || value.length<2){
var txt = "Incorrect input. Please enter correct age.";
alert(txt);
return false;
}
return true;
}


function validateNoOfDigits3(value){
if (value.length<8){
alert("Incorrect Password Length. Please enter password with min 8 characters");
return false;
}
return true;
}

function validatePasswordEqual(value){
if (value != Password.name){
alert("Incorrect Password. Double check passwords match");
return false;
}
return true;
}

function validatePassword(value) {
    var error = "";
    var illegalChars = /[\W_]/; // allow only letters and numbers

    if (value == "") {
        error = "You didn't enter a password.\n";
    } else if (value.length > 8) {
        error = "The password is the wrong length. \n";
    } else if (illegalChars.test(value)) {
        error = "The password contains illegal characters.\n";
    } else if (!((value.search(/(a-z)+/)) && (value.search(/(0-9)+/)))) {
        error = "The password must contain at least one numeral.\n";
    } 
   return error;
}
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
        <script language ="Javascript" src="js/Function2.js"></script>
        <link rel = "stylesheet" type = "text/css" href = "css/index.css" />

    </head>
    <body>
        <form onsubmit="validateAll(this)">
Firstname: <input type="text" name="Firstname"/><br/>

Surname: <input type="text" name="Surname"/><br/>

Age: <input type="text" name="Age"/><br/>

Username: <input type="text" name="Username"/><br/>

Password: (number and letters, min 8 characters):
<input type="text" name="pass1"/> <br/>

Repeat Password:
<input type="text" name="pass2"/> <br/>

<input type="submit" value="Submit Details" name="Button1"/>

</form>

</body>
</html>

Bobon,

You are on the right lines. Just a few things to fix.

  1. You need to pass the form fields' values to the validator functions rather than the fields themselves (DOM elements).
  2. Ensure that each of the individual validator functions returns true (for OK) or false (for error). Most of them are fine but validatePassword returns an error string.
  3. In validateAll(), you need to do something with the results returned by the individual validator functions. Simplest thing is :
    • on success, allow the checks to continue
    • on failure, return false (bomb out of validateAll())

You can also reduce the number of functions considerably by creating a generalised validateNoOfDigits() to replace validateNoOfDigits1(), validateNoOfDigits2(), validateNoOfDigits3() and validateNotEmpty().

Here's a way to formulate it based on your original code:

function validateAll(myForm){
	if( !validateNoOfDigits(1, myForm.Firstname.value, 'Name must be at least %s characters') ){ return false; }
	if( !validateNoOfDigits(1, myForm.Surname.value, 'Surname must be at least %s characters') ) { return false; } 
	if( !validateNoOfDigits(2, myForm.Age.value, 'Age must be at least %s digits') ) { return false; }
	if( !validateNumber(18, myForm.Age.value, 'Sorry you must be at least %s') ) { return false; }
	if( !validateNoOfDigits(0, myForm.Username.value, 'Name must be at least %s characters') ) { return false; }
	if( !validatePassword(8, myForm.pass1.value) ) { return false; }
	if( !validatePasswordEqual(myForm.pass1.value, myForm.pass2.value) ) { return false; }
	return true;
}
function validateNoOfDigits(n, value, errorMessage){
	if (value.length < n){
		alert(errorMessage.replace('%s', n));
		return false;
   }
   return true;
}
function validateNumber(n, value, errorMessage){
	var checkvalue = Number(value);
	if (isNaN(checkvalue)) {
		alert('Age must be a number');
		return false;
	}
	if (checkvalue < n) {
		alert(errorMessage.replace('%s', n));
		return false;
	}
	return true;
}
function validatePasswordEqual(value1, value2){
	if (value1 != value2) {
		alert("Double check passwords do not match");
		return false;
	}
	return true;
}
function validatePassword(n, value) {
	var illegalChars = /[\W_]/; // allow only letters and numbers
	if ( !validateNoOfDigits(1, value, "You didn't enter a password.") ) { return false; }
	else if ( !validateNoOfDigits(n, value, "Password must be at least %s characters")) { return false; }
	else if (illegalChars.test(value)) { alert("The password contains illegal characters."); return false; }
	else if ( !((value.search(/(a-z)+/)) && (value.search(/(0-9)+/))) ) { alert("The password must contain at least one numeral."); return false; }
	return true;
}

I've not validated the regular expressions in validatePassword().

Airshow

Airshow, apologies for the delay. I haven't been doing much JavaScript of late. Thanks a million for the reply. I understand what you did and I got it working.

I just have one question for you. Say for example, you want the characters of 'name' to be text and to prompt a user to re-enter if he/she enters a numerical value. I typed in the code below. Just wondering what would you put into the form validation to signify any number, if you know what I mean. Cheers again

function validateEntry(n, value, errorMessage){

      if (value != text){

      alert(errorMessage.replace('%s', n));

      return false;

      }

      return true;

      }

Bobon,

For this sort of test you really need to learn how to write your own "regular expressions". These are abstracted representations of string patterns against which you wish to test a string, or perform a (partial) replacement, or one of several other things. A couple of regular expressions appear in your original post above.

Try running these statements for example:

var pattern = /^[a-zA-Z]+$/;//whole string lower-case/upper-case alphabetic, no spaces
var pattern2 = /^[a-zA-Z\s]+$/;//whole string lower-case/upper-case alphabetic, spaces allowed
alert(pattern.test('ABC'));
alert(pattern2.test('ABC DEF'));
alert(pattern.test('ABC DEF'));
alert(pattern.test('99ABC'));
alert(pattern.test('ABC99'));
alert(pattern.test('99'));
alert(pattern.test('99.9'));

In your form validator, you would use an expression such as:

if(!pattern.test(myForm.Firstname.value)){ return false; }

Regular expressions are well documented on we web. Make sure that you research Javascript regular expressions, because other languages also have them but with subtle differences.

Airshow

Thats no problem Airshow. I won't go ahead with regular expressions yet as I want to try and understand the basics first.

With regards to an email, I was just wondering how would you display the restrictions in the function?

So I understand it would start with something like the code below.

#
if( !validateEmail(email, myForm.Email.value, 'Invalid email address entered') ) { return false; }
function validateEmail(value, errorMessage)
      if (value [B]does not contain '@' symbol[/B]){
       
      alert(errorMessage.replace( n));
    
      return false;
      
      }
      return true;

      }

Bobon,

Email addresses really do benefit from validation by regular expression. Try Googling eg. "javascript email regex" for some ideas. There is no shortage of results.

I suggest using if( !validateEmail(myForm.Email.value, 'Invalid email address entered') ) { return false; } , and a function of the general form :

function validateEmail(value, errorMessage) {
    var pattern=/^([a-zA-Z0-9_.-])+@([a-zA-Z0-9_.-])+\.([a-zA-Z])+([a-zA-Z])+/; //I chose this from a top ranking Google result 
    if ( !pattern.test(value) ) {
        alert(errorMessage);
        return false;
    }
    return true;
}

Whatever regex you decide on, be sure to test it thoroughly. Look through your own address book for test data (ie the email addresses of your own contacts).

Airshow

Thanks Airshow, I'll have a look at that. I've found a decent link that explains regular expressions so will have a look at that. Thanks again mate.

Regular expressions: I find they are my best friend or my worst enemy depending on how bright I feel on the day.

So don't worry too much if you don't cotton onto them immediately.

Airshow

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.