Tutorial Ref.com

Javascript Validate Name Field:Check Name Field After User Submits Form

Here is a simple tutorial on how to use Javascript to validate a form's name field. In this tutorial I'll show how to display the error beside the name field rather than pop-up the error message using the alert function. The error will display stating there is no name in the name field (I use a username field; however, the code can easily apply to a name field) in the error region when the user clicks on the submit button. When the user enters a name in the name field and then resubmits the error is no longer displayed.

Here is the HTML form:

1
2
3
4
5
6
7
8
<form name="register" method="POST" action="connect2.php" onsubmit="return checkWholeForm(this)">
    <fieldset>
        <div id="usernameField"><label style="padding-left:20px;" for="username">username:</label><input type="text" name="username" id="username" size="30" maxlength="45" /><span id="errorMesUsername"></span></div>
        <div><label style="padding-left:20px;" for="pass">password:</label><input type="password" name="pass" id="pass" size="30" maxlength="45" /></div>
        <label for="email">email:</label><input type="text" name="email" id="email" size="30" maxlength="45" /><br />
    </fieldset>
    <input type="submit" value="submit" name="submit" />
</form>

Basically, when the user clicks on the submit button the browser is expecting some return value from the checkWholeForm() function. The word 'this' is referring to the form as it's an object. In other words, 'this object' is the form. Notice There is a span section beside the username's input field.

1
<span id="errorMesUsername"></span>

There is nothing displayed to the username when the form is opened as this is where Javascript will return the error message if there is no name entered in the field.

Validate the Form Using Javascript function

Here is the Javascript function for checkWholeForm():

1
2
3
4
5
6
7
8
function checkWholeForm(theForm) {
 
   with(theForm) {
       checkUsername(username.value);
   }
 
return true;
}

Notice the above uses a Javascript with() function. All this is saying is that all properties within the curly brackets {} will use the 'theForm' object. In other words, this 'username' is the property of 'theForm' object. The 'username' is the value of the 'name' attribute in the input tag as follows:

1
<input type="text" name="username" id="username" size="30" maxlength="45" />

If we chose not to use the with() function then we could write the checkWholeForm(theForm) as follows;

1
2
3
4
5
6
function checkWholeForm(theForm) {
 
       checkUsername(theForm.username.value);
 
return true;
}

If we were to create additional validations such as for the password field and use the with() function then we could write the checkWholeForm(theForm) as follows:

1
2
3
4
5
6
7
8
9
function checkWholeForm(theForm) {
 
   with(theForm) {
       checkUsername(username.value);
       checkPassword(pass.value);
   }
 
return true;
}

The 'pass.value' is passing the value of the input of the password field to the checkPassword() function. The 'pass' is the value of the 'name' attribute of the 'input' tag. This function is incomplete as it will eventually be validating the password using PREG (Perl Regular Expressions).

1
2
3
4
5
6
7
8
9
10
11
12
13
function checkUsername (usernameVal) {
 this.errorMes = document.getElementById("errorMesUsername");
 
 var error = "";
 if (usernameVal == "") {
    error = "You didn't enter a username.\n";
     this.errorMes.innerHTML = error;
 } else if (this.errorMes.innerHTML != "") {
     this.errorMes.innerHTML = "";
 } else {
     return true;
 }
}

Display error message if no name is entered

The first line with 'this.errorMes' is simply creating a local variable. You could create a variable as 'var errorMes' instead. I program primarily in PHP so I'm used to using the term 'this' when referring to objects. We are getting the element by the id's value. In other words, the span tag's attribute 'id' has a value of 'errorMesUsername'. The span tag as you will notice is immediately after the input tag of the user field. This is where the error will display if the user did not enter any value in the user field. The reference to this DOM will be used later in the conditional statements.

Then in the next line we make the variable 'error' equal to nothing in case there is a previous value attached to it. Then we check for some conditions. Since this function (i.e. checkUsername()) is checking to see if the user entered any text the first conditional statement is "if (usernameVal == "")". Don't forget the double equal (i.e.'==') signs for conditional statements. This is different than assigning a value to variable where you only need one equal (i.e.'=') sign. If it turns out that the user did not enter any text in the username field then we assign the value of variable 'error' which equals "You didn't enter a username.\n" to be placed within the span tag (i.e. innerHTML) where the attribute 'id' equals 'errorMesUsername'.

Delete error message if name is entered

The second conditional "else if (this.errorMes.innerHMTL != "")" is checking to see if there is any value within the span tag. In other words, if there is any error displayed. We need this conditional when the user then enters a name in the field after reading the error message and then resubmits the form. To further explain, if the condition 'usernameVal == ""' returns false or, in other words, if the there is now some text that was entered by the user in the name field then go to the next conditional which is where we are at. Since there is not some entered text in the name field we need to check to see if there is an error displayed in the span tags and if there is then we need to delete it (i.e. not display it). We do this by assigning the value of the span tag to equal to nothing with this line 'this.errorMes.innerHTML = ""'.

As an extra precaution we could have written this 'else if' condition as 'else if (this.errorMes.innerHTML != "" && usernameVal != "")'. The two ampersands are an extra condition that must be met. 'usernameVal != "" means if the variable 'usernameVal' does not equal to nothing or more simply put if the variable 'usernameVal' equals to something (i.e. some text was entered in the name field). Double negative equals a positive.

Just as a note, we could have used the Javascript function onchange() instead of using this conditional statement. onchange() function will check if the user starts typing any text in the name field. As soon as the user types any text then we can return another function value based on what the user starts typing.

The last 'else' conditional is simply a catchall in case the other conditions don't pass for whatever reason.

So the entire Javascript code looks like:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
function checkWholeForm(theForm) {
 
   with(theForm) {
       checkUsername(username.value);
   }
 
return true;
}
 
function checkUsername (usernameVal) {
 this.errorMes = document.getElementById("errorMesUsername");
 
 var error = "";
 if (usernameVal == "") {
    error = "You didn't enter a username.\n";
     this.errorMes.innerHTML = error;
 } else if (this.errorMes.innerHTML != "") {
     this.errorMes.innerHTML = "";
 } else {
     return true;
 }
}

This is a basic example of Javascript validating a name field. We'll go into more validation checks for the form's fields in upcoming tutorials.

TutorialRef.com - tutorials, guides, how-tos, helps