JavaScript Form Validation

 

JavaScript validation check form before submitting to server all field in form filled properly or not. If any validation fails, it stops submitting form to server. It returns a error message to user about failure of form submission. It indicates error focus on form where error is found on field.

User can understand what real problem occurred in form by seeing error on field and they fill again proper value in field and can submit it again.

JavaScript validation have good thing, it is executed on client side. This will save server side process and resources of server. Server will not busy with this work of form validation.

JavaScript validation is much faster and instant result provide to user. This increases the submission process to server with valuable data.

 

JavaScript Validation

Required Validation

Required Validation means field should not submit empty to the server. It should contain any record, characters numbers or special characters before submitting to the server.

Demo

<html>
<head>
<title>Required Validation</title>
<script>
function validate()
{
  var vUser=trim(document.frm.sUser.value);
  var vPwd=trim(document.frm.sPwd.value);

  if(vUser=="")
  {
    alert("User Name Field is Empty");
    document.frm.sUser.focus();
    return false;
  }
  else if(vPwd=="")
  {
   alert("Password Field is Empty");
   document.frm.sPwd.focus();
   return false;
  }
}

function trim(s) {
    return s.replace( /^s*/, "" ).replace( /s*$/, "" );
}

</script>
</head>

<body>
<form name="frm" onSubmit="return validate();">
User Name <input type="text" name="sUser" /><br>
Password <input type="password" name="sPwd" /><br>
<input type="submit" name="goTo" value="Submit"/>
</form>
</body>
</html>

Number or Integer Validation

Number Validation in JavaScript should only contain numeric digits and contain no alpha characters or not any special characters. This number can be 0-9. Number Validation is used in phone number validation, currency check or some particular requirement.

Demo

<html>
<head>
<title>Number Integer Validation</title>
<script>

function validate()
{
  var dValidate=document.frm.numberValidate.value;
  if(dValidate=="")
  {
    alert("Number Field is empty")
    return false;
  }
  else if(isDigits(dValidate)==false)
  {
   alert("Field is not numeric")
   return false;
  }
}


function isDigits(argvalue) {
    argvalue = argvalue.toString();
    var validChars = "0123456789";
    var startFrom = 0;
    if (argvalue.substring(0, 2) == "0x") {
       validChars = "0123456789abcdefABCDEF";
       startFrom = 2;
    } else if (argvalue.charAt(0) == "0") {
       validChars = "01234567";
       startFrom = 1;
    }
    for (var n = 0; n < argvalue.length; n++) {
        if (validChars.indexOf(argvalue.substring(n, n+1)) == -1) return false;
    }
  return true;
}
</script>
</head>

<body>
<form name="frm" onSubmit="return validate();">
Number <input type="text" name="numberValidate" />
<input type="submit" name="goTo" value="Number Validate" />
</form>
</body>
</html>

Date Validation

Date Validation should used for data format. Date should either not empty or not in wrong format before submitting to the server. Date Validation is used for late Date submission, event start, event end, reminders date, or date of birth.

Demo

<html>
<head>
<title>Date Validation</title>
<script>
function validate()
{
  var dValidate=document.frm.dateValidate.value;
  if(dValidate!="")
  {
    var arDValidate=dValidate.split("/");
    if(arDValidate.length==3)
    {
      if(arDValidate[0].length!=2 || (arDValidate[0]>32))
      {
         alert("Wrong Date format");
         return false;
      }
      else if(arDValidate[1].length!=2 || (arDValidate[1]>13))
      {
         alert("Wrong Month format");
         return false;
      }
      else if(arDValidate[2].length!=4 || (arDValidate[2]<1900))
      {
         alert("Wrong Year format");
         return false;
      }
      else
      {
        var dateDate=new Date(arDValidate[2],arDValidate[1]-1,arDValidate[0]);
        if((arDValidate[0]!=dateDate.getDate()))
        {
          alert("Wrong Date Enter e.g date month year is not correct 31 feb 2009");
          return false;
        }
      }
    }
    else
    {
    alert("Wrong Format");
    return false;
    }
  }
  else
  {
   alert("Date is blank");
   return false;
  }
}

</script>
</head>

<body>
<form name="frm" onSubmit="return validate();">
mm/dd/yyyy <input type="text" name="dateValidate" />
<input type="submit" name="goTo" value="Date Validate" />
</form>
</body>
</html>

Email Validation

Email Validation is used for checking proper email format. Email contains one dot and one @. This should be present in any email format with some text. It also checks @ start with some characters, and dot has some characters also.

Demo

<html>
<head>
<title>Email Validation</title>
<script>
function validate()
{
  var dValidate=document.frm.emailValidate.value;
  if(dValidate=="")
  {
    alert("Email Field is empty")
    return false;
  }
  else if(checkEmail(dValidate)==false)
  {
   alert("Email Format is not correct")
   return false;
  }
}

function checkEmail(emailStr) {
       if (emailStr.length == 0) {
           return true;
       }
       var emailPat=/^(.+)@(.+)$/;
       var specialChars="\(\)<>@,;:\\".\[]";
       var validChars="[^\s" + specialChars + "]";
       var quotedUser="("[^"]*")";
       var ipDomainPat=/^(d{1,3})[.](d{1,3})[.](d{1,3})[.](d{1,3})$/;
       var atom=validChars + "+";
       var word="(" + atom + "|" + quotedUser + ")";
       var userPat=new RegExp("^" + word + "(\." + word + ")*$");
       var domainPat=new RegExp("^" + atom + "(\." + atom + ")*$");
       var matchArray=emailStr.match(emailPat);
       if (matchArray == null) {
           return false;
       }
       var user=matchArray[1];
       var domain=matchArray[2];
       if (user.match(userPat) == null) {
           return false;
       }
       var IPArray = domain.match(ipDomainPat);
       if (IPArray != null) {
           for (var i = 1; i <= 4; i++) {
              if (IPArray[i] > 255) {
                 return false;
              }
           }
           return true;
       }
       var domainArray=domain.match(domainPat);
       if (domainArray == null) {
           return false;
       }
       var atomPat=new RegExp(atom,"g");
       var domArr=domain.match(atomPat);
       var len=domArr.length;
       if ((domArr[domArr.length-1].length < 2) ||
           (domArr[domArr.length-1].length > 3)) {
           return false;
       }
       if (len < 2) {
           return false;
       }
       return true;
}
</script>
</head>

<body>
<form name="frm" onSubmit="return validate();">
Email <input type="text" name="emailValidate" />
<input type="submit" name="goTo" value="Email Validate" />
</form>
</body>
</html>

Alpha Character Validation

Alpha character starts with a to z characters with lower case and upper case. But it does not contain any special symbol and any numeric value. This validation is used for first name, last name country, city name and other particular propose.

Demo

<html>
<head>
<title>Alpha number Validation</title>
<script>

function validate()
{
  var dValidate=document.frm.alphaValidate.value;
  if(dValidate=="")
  {
    alert("Alpha Field is empty")
    return false;
  }
  else if(isAlpha(dValidate)==false)
  {
   alert("Field is not alpha character")
   return false;
  }
}


function isAlpha(argvalue) {
  argvalue = argvalue.toString();
  var validChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";

    for (var n = 0; n < argvalue.length; n++) {
        if (validChars.indexOf(argvalue.substring(n, n+1)) == -1)
         return false;
    }
  return true;
}
</script>
</head>

<body>
<form name="frm" onSubmit="return validate();">
Alpha Character <input type="text" name="alphaValidate" />
<input type="submit" name="goTo" value="Alpha Validate" />
</form>

</body>
</html>

We have example of JavaScript form validation. This example work with required validation, email validation, numeric integer validation and date validation.

 

9 Responses to “JavaScript Form Validation”

  1. RaiulBaztepo says:

    Hello!
    Very Interesting post! Thank you for such interesting resource!
    PS: Sorry for my bad english, I’v just started to learn this language ;)
    See you!
    Your, Raiul Baztepo

  2. raaz says:

    THX A LOT…… very good website… i just want to promote this website to frnds and colleagues…..

  3. Bharat Verma says:

    Bugs in the date validation

    1.) (arDValidate[1]>13)) it should be (arDValidate[1]>12))

    2.) (arDValidate[0]>32) it should be (arDValidate[0]>31)

    else it can take any year like 32/13/XXXX

    Thanks contact me at bindian0509 [at] gmail.com

  4. GeorgeS says:

    All very useful.
    One question – Do you have an example of a single js script to cover 1 single form with all these fields in it?
    You use the same function name each time & apply it to onsubmit or to the Submit value, but if there’s only 1 form & 1 submit button, we have to try to integrate these scriptlets into one.
    Bookmarked anyway. Thx. ;-)

  5. SHAHUL says:

    really bravo! in my point of view excellent website to learn much..thanks for came into world…

  6. mano says:

    Its really very helpful to us….. thank you very much…..

  7. shahid says:

    its really very helpful to us …..thanks

  8. akki says:

    hi could anyone tell me the form which i have created contains name,father name,dob,gender using drop down list,email,address should be validated in a single form using javascript how to do it

  9. gowtham c says:

    i want to validate e-mail address in javascript,but without using regular expression, which i had and i want to validate using indexOf(), or some other inbuilt functions…must not using regular expression..can any one help me ???

Leave a Reply