Wednesday, December 29, 2010

Javascript form validation (all error in one popup window)

This tutorial will show you how to create a JavaScript-enabled form that checks whether a user has filled in the form correctly before it's sent to the server. If anything goes wrong then a popup window will display with the errors.

First create a html page with your any favaourite text editor and write the following code in that document.

<script type="text/javascript">
function validate_form(thisform){
    var errors='';
    var fname = document.form1.firstname.value;
    if(fname.length < 5){
        errors= "Please fill the first name !\n";
    var lname = document.form1.lastname.value;
    if(lname.length < 4){
        errors+= "Please fill the last name !\n";
    if(!errors == ''){
        alert("The following error(s) occured:\n\n" +errors);
        return false;
        } else {
        return true;

<form action="submit.htm" name="form1" onsubmit="return validate_form(this)" method="post">
<table cellpadding="2" cellspacing="3">
        <td>First Name</td>
        <td><input type="text" name="firstname" size="30"></td>
        <td>Last Name</td>
        <td><input type="text" name="lastname" size="30"></td>
        <td colspan="3" align="center"><input type="submit" value="Submit"></td>

It will show all error in one popup window..

No comments:

Post a Comment