Did you find this useful?
Socialize it today.


JavaScript Form Validation

Wednesday, May 02, 2012

Any dynamic website you come across will have some type of form input to collect information from your visitors. Normally, this collected data is passed to a server side scripting language for processing. This processing requires that data be sent back to the web server, which introduces delays while the information travels over the Internet to the server, is processed by the server, and then returns back to the user's client browser. This is normally acceptable, assuming that the data the was submitted is valid. However, in a situation where the user did not input valid information, the delay could and should have been avoided. Using client side JavaScript is an efficient way to validate the user input before submitting it back to the web server. By validating the user's input before the information is submitted, no additional delays and/or unnecessary processing power is introduced into the process. By validating user input, invalid data is filtered out prior to sending data to the web server. Client side form validation is generally done using JavaScript code. You will find that JavaScript form validation will save a lot of time and server resources.

Form data that typically are checked by a JavaScript could be:

  • Required fields
  • Valid data types
  • Valid user name
  • Valid password
  • Valid e-mail address
  • Valid phone number

Required Fields

The function below checks if a field has been left empty. If the field is blank, an alert popup is triggered and the function returns false which will not allow the form to be submitted.

<script type="text/javascript">
function validateRequired()
{
var x=document.forms["form1"]["name"].value;
if (x==null || x=="")
  {
  alert("Name cannot be blank.");
  return false;
  }
}
</script>

<form name="form1" action="process.aspx" 
         onsubmit="return validateRequired()" method="post">
    Name: <input type="text" name="name">
    <input type="submit" value="Submit">
</form>


Email Validation

The function below checks for the syntax of an email. The input must contain an @ sign and at least one dot (.). Also, the @ must not be the first character of the email address, and the last dot must be located after the @ sign, and minimum 2 characters before the end.


<script type="text/javascript">

function validateEmail()
{
    var x=document.forms["form1"]["email"].value;
    var at=x.indexOf("@");
    var dot=x.lastIndexOf(".");
    if (at<1 || dot<at+2 || dot+2>=x.length)
    {
        alert("Not a valid e-mail address");
        return false;
    }
}

</script>

<form name="form1" action="process.aspx" 
    onsubmit="return validateEmail();" method="post">
        Email: <input type="text" name="email">
    <input type="submit" value="Submit">
</form>


Username and Password

It is very common for you to require that your user's supply a username and password with a minimum number of characters. Here is an example of how you can validate the length of the user's input.


<script type="text/javascript">
    
function validateLength(x, y) {
    if (x.value.length < 6 || 
        y.value.length < 6) {
    alert("UserName and Password does 
            not meet requirements!");
      return false;
    }
    return true;
}

</script>

<form>
  UserName: <input type="text" id="username"/><br/>
  Password: <input type="text" id="password"/>
  <input type="button" 
	onclick="validateLength(
      document.getElementById('username'), 
      document.getElementById('password'))"
	value="Submit" />
</form>

Please help us spread the word by socializing it today!

email contact us

Did you find something wrong with the information on this page? Please take a moment to report it to us so that we can continue to improve the quality of the information on this site. Click here to report an issue with this page.



Recommended Books & Training Resources

HTML CSS and JavaScript Editor JavaScript and jQuery: The Missing Manual Professional JavaScript for Web Developers