Javascript Tutorial, tips, guides. Victor Kimura
Javascript Tutorial 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.
- Related Videos
- Related Articles
- Ask / Related Q&A
- One Big Reason to Limit Your Use of JavaScript
- Ajax Form Validation and Thread-safe Ajax
- Javascript Validate Name Field
- The Power of JavaScript in Web Design
- Increase Your Sales by Converting Rss/xml to Javascript
- Using Php to Validate Form Fields
- Basic Javascript
- Asynchronous Javascript and Xml – Technology to Increase Website Interactivity!




A reason to smile for All PHP Developers
By: Mahendra Sharma | 28/11/2009The PHP developers have full right to smile today due to their choice of career as PHP programmers. This article is highlighting some key factors on how this language is bypassing all other in the website development world.
How to Solve the Registry Errors
By: janson | 27/11/2009The Registry of Windows is the most important for the working of the computer system due to it stores valuable data which can cause serious loss in performance of the system. The registry files of Windows are set to save the configuration settings of Windows and they are spread around on the hard disk. To solve the errors of them was absolute a Herculean task.
Gravity Jack Software Studio is a new venture that is pushing the envelope in the mobile software development arena
By: Adam Chronister | 26/11/2009Gravity Jack opened offices this month in Liberty Lake and is currently filing patents regarding a tightly-kept secret project that is expected to revolutionize the way people interact with mobile computing platforms such as Apple’s iPhone and Google’s Android.
PHP and Open Source, Keys to build complex but Affordable websites
By: Mahendra Sharma | 26/11/2009Gone are the days when high tech programmers and high profile companies were required to be engaged to develop a complex system on web. Open Source and especially PHP developers have changed the scenario. Every other day you can find new software available as open source developed by PHP programmers. Essential thing is such software is available for free or at nominal cost.
Java Application development India
By: Rightway Solution | 25/11/2009Java is most suitable for creating Enterprise Applications for its flexibility and control. JAVA is used to create wide range of application with an extensive functionality.
Understanding the Typical Structure of Software Testing Process
By: yogindernath | 25/11/2009Understanding the Typical Structure of Software Testing Process
CRM Customisation
By: Manny de Sousa | 24/11/2009Next Generation CRM platforms need to offer full customisation. With the number of flexible design tools and components for .net and other development platforms there are no excuses for CRM providers not to offer truly simple customisation tools that can be used by non IT minded individuals
Computer technology - How to make your computer work faster?
By: janson | 24/11/2009Computer slows down over time due to every day use. It makes simple tasks start taking minutes or hours to finish. In order to make the computer work effectively and quickly, it is necessary for the computer users to do something to improve the performance of the computer.
Windbg Minidump Tutorial:Setting up & Reading Minidump Files
By: Victor Kimura | 07/07/2009 | ProgrammingWindgb 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.
Thunderbird Cannot Connect to Server-Download Email Problem
By: Victor Kimura | 07/07/2009 | SoftwareThunderbird cannot connect to server problem. How to resolve the problem if you have trouble downloading email from the server and the hour glass figure keeps displaying. Could be related to a virus, or Norton attempting to scan the infected email or a process error of Thunderbird.
Javascript Validate Name Field
By: Victor Kimura | 07/07/2009 | ProgrammingSimple 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 | ProgrammingA 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 | ProgrammingAutoIt 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 | ProgrammingAutoIt 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 | NetworksIMAP 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.