Simple Javascript validator:
You have a big form and you want to validate user inputs. Its really a pain to write lot of code for date check, for email validation and many more checks. Lets try Simple JavaScript validator and make our code clean.
Validate you form in few steps:
1)Import Javascript validator and css
Write this code inside head tags.
<script type="text/javascript" src="http://zeustek.com/utils/validator/validation.js"></script>
<link rel="stylesheet" type="text/css" href="http://zeustek.com/utils/validator/validation.css">
2)Create a List of all types of validations
/***************************
Validation array :
Ist Param - Type of Check .
2nd Param - Form Field Name , for Equal: use both fields separated by “|”
3rd Param - Error Message if check Fails .
4th Param - Minimum required length of field .
(For Dates : 4th Param - Date Format . )
5th Param - Maximum required length of field .
****************************/
function validationCheck(){
var validations = new Array() ;
validations[0] = new Array("REQUIRED" , "fieldName1" , "Name is required");
validations[1] = new Array("ALPHA" , "A1" , " invalid Name" , "0", "30") ;
validations[2] = new Array("REQUIRED" , "A2" , "Phone is required") ;
validations[3] = new Array("NUMBER" , "A2" , " invalid Phone" , "0", "10") ;
validations[4] = new Array("EMAIL" , "A3" , "Invalid Email") ;
validations[5] = new Array("DATE" , "A4" , "Invalid Date- Use DD/MM/YYYY" , "DD/MM/YYYY") ;
validations[6] = new Array("DATE" , "A5" , "Invalid Date- Use MM/DD/YYYY" , "MM/DD/YYYY") ;
validations[7] = new Array("EQUAL" , "A3|A8" , "NOT SAME" ) ;
var showAllErrors =true ; // true if you want to show all errors , else set it to false
/*****************************************************
Ist Param - Form name .
2nd Param - Validations Array .
3rd Param - Whether to show all params or one by one.
4th Param - Error Color. GREEN, RED, BLUE,BLACK
*******************************************************/
if( validateForm(document.testForm, validations,showAllErrors, "RED" )){
document.testForm.submit();
}
3)Create a div for showing errors:
<div id="err"></div>
4)On click of submit call the validationCheck function
Thanks
vinay