Remember Me
forgot your password?

Javascript Validate Name Field

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:

<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.

<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():

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:

<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;

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:

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).

function checkUsername (usernameVal) {
this.errorMes = document.getElementById("errorMesUsername");

var error = "";
if (usernameVal == "") {
error = "You didn't enter a username.n";
this.errorMes[removed] = error;
} else if (this.errorMes[removed] != "") {
this.errorMes[removed] = "";
} else {
return true;
}
}

DISPALY 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[removed] = ""'.

As an extra precaution we could have written this 'else if' condition as 'else if (this.errorMes[removed] != "" && 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:

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[removed] = error;
} else if (this.errorMes[removed] != "") {
this.errorMes[removed] = "";
} 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.

Victor Kimura

Javascript Tutorial, tips, guides. Victor Kimura
Javascript Tutorial Javascript Validate Name Field

Rate this Article: 0 / 5 stars - 0 vote(s)
Print Email Re-Publish

Add new Comment



Captcha

  • Latest Programming Articles
  • More from Victor Kimura

An Event Registration Service Can Eliminate Much Event Planning Stress

By: Brad Robert | 06/11/2009
Event-Registration-Service.com is the leading online event registration, event planning and event management software for all types of businesses and organizations.

HTML Guestbook in ASP.Net

By: pons_saravanan | 05/11/2009
A very simple guest book without any Database storage.

Himfr.com reports the new sail will be put on the market in January next year

By: chenxiao | 05/11/2009
the new sail will be put on the market in January next year.

iPhone Applications at Its Best

By: Arun Kumar | 05/11/2009
The Apple iPhone has been deemed the gadget of the decade. It’s such kind of a power product from the house of Apple that has really changed the way people communicate. In the last few years we have seen several mobile handsets, PDAs and pocket PCs from the big labels, but the wonder that Apple has done is really something special, something beyond everyone’s imagination.

Diexon - Game Programming

By: Matthew | 04/11/2009
Diexon is a game programming company that is always look for artists to help make games.

Java Developers and the power of Java

By: zekin | 03/11/2009
Java developers who had been working on Java platform must be aware of the power of this platform. Although, some of the live application of Java gives more idea on what more can be done with the Java application development platform.

Dot Net Development: An Integral Part of Web Application Development

By: Tyler Moon | 03/11/2009
Dot Net Development has become an integral part of web application development and is therefore a dependable, scalable and consistent environment for web application development. Dot Net platform decreases the time and cost linked with developing and conserving business applications.

Dot Net Development: An Integral Part of Web Application Development

By: Tyler Moon | 03/11/2009
Dot Net Development has become an integral part of web application development and is therefore a dependable, scalable and consistent environment for web application development. Dot Net platform decreases the time and cost linked with developing and conserving business applications.

Windbg Minidump Tutorial:Setting up & Reading Minidump Files

By: Victor Kimura | 07/07/2009 | Programming
Windgb Minidump tutorial to set up and read minidump files (.dmp). Setting Symbol File Path. Output of Windbg command. windbg.exe -z [file path to minidump file.dmp] -c !analyze -v.

Javascript Validate Name Field

By: Victor Kimura | 07/07/2009 | Programming
Simple Javascript tutorial on validating a name field. Checks to see if there is a value in the name field with Javascript after the user submits a form.

PHP PDO MySQL:Simple Example Connecting to MySQL with PDO Class

By: Victor Kimura | 19/06/2009 | Programming
A simple example on how to connect to a MySQL database with PHP PDO class. Possible errors in coding using PDO and short discussion on PDO error handling from MySQL results.

AutoIt: How to copy a file's contents and paste using the clipboard

By: Victor Kimura | 19/06/2009 | Programming
AutoIt tutorial-How to copy text and paste it from the clipboard using variables. How to copy a file and its name to another directory.

AutoIt:Connect to Access Databases:mdb & accdb files

By: Victor Kimura | 15/06/2009 | Programming
AutoIt tutorial discussing how to connect to an Access 2007 and 2003 database. .mdb and .accdb file extensions connections are made. How to retrieve a single record and place a field's value into a variable.

IMAP Multiple Connections / Processes Problem:Site Down

By: Victor Kimura | 15/06/2009 | Networks
IMAP with multiple connections can cause problems and bring down your website. This could be due to multiple IMAP processes that linger. You need to kill these IMAP processes in the control panel.

Web Hosting Transfer Domain:Transferring Domain to Another Provider or Account

By: Victor Kimura | 11/06/2009 | Networks
How to transfer domains to another web hosting provider or to another web hosting account (with the same provider). Step-by-step instructions for transferring your domain safely.

Submit Your Articles Free: Signup
Article Categories




Use of this web site constitutes acceptance of the Terms Of Use and Privacy Policy | User published content is licensed under a Creative Commons License.
Copyright © 2005-2008 Free Articles by ArticlesBase.com, All rights reserved. (0.13, 1, w1)