Added: 26 February, 2008
Group: JavaScript
Form field validation with JavaScript
Author: Alex
page: 1

Form field validation with JavaScript

When you create submit forms where users are required to enter some info it's very useful to check if those fields are entered. With this simple JavaScript function we can easily manage form validation.

First we need a form so let's create one:

<form method="post" action="action.php" onsubmit="return validate( );">
<input type="text" name="name">
<input type="submit" name="Submit" value="Submit">

As you can see in code above this form uses onSubmit event and calling validate JavaScript function. The value we are providing to the script is "Submit" and if that value is sent the JavaScript function is executed.

Now, we need to create the JavaScript function. Place following code in <head> of your webpage.

<script type="text/javascript">
function validate( )
valid = true;

if ( == "")
alert ( "Name is required field !" );
valid = false;
return valid;


This code check if form field contains any data and if user skip entering anything alert message displays with information that, in this case, Name field is required.

Next step can be extending this script and adding check for each required field, such as email address or any other necessary data.

Using JavaScript for field validation is easy but it can cause problems because of potential security risk that can allow hackers to bypass it.

GO to: Page 1 : Form field validation with JavaScript This tutorial is copyrighted. Partial duplication or full duplication is prohibited and illegal. Translation or usage of any kind without author�s permission is illegal.