Complete validation of forms with regular expressions and JavaScript

Source: Internet
Author: User
Tags date format array continue empty eval mail trim
Javascript| Regular

Code:<!--
When using, save the following JavaScript code in a single JS file.
1. Form requirements
<form name= "FormName" ></form>
All of the following types of fields in the form will be validated in turn, all validation is to remove the leading and suffix spaces, and note that the case is case-sensitive.
2, null value verification
Any field in the form plus the Emptyinfo property verifies that the field is empty (can be used concurrently with the maximum length validation \ General authentication method).
No this property is considered to allow null values for this field.
such as: <input type= "text" name= "fieldnamename" emptyinfo= field can not be empty! ">
3. Maximum length verification (can be used at the same time as null verification, general authentication method):
<input type= "text" name= "Fieldnamename" maxlength= "" lengthinfo= "maximum length can not exceed 20! ">
Or, <textarea maxlength= "lengthinfo=" the maximum length can not exceed 2000! ">
3, the General verification method (do not verify the null value):
such as: <input type= "text" validator= "^ (19|20) [0-9]{2}$" errorinfo= "Incorrect year!" >
4. Standard verification (not used in conjunction with other verification methods):
All are implemented through the <input type= "hidden", and the Name property is not required to avoid submitting to the server.
4.1. Legal Date Verification:
<input type= "text" name= "Yearfieldname" value= ">" Note: This can also be <select name= "Yearfieldname" ></select ", with the same
<input type= "text" name= "Monthfieldname" value= ">"
<input type= "text" name= "Dayfieldname" value= ">"
<input type= "hidden" validatortype= "Dategroup" year= "Yearfieldname" month= "Monthfieldname" day= "DayfieldName" Errorinfo= "not the right date!" >
Yearfieldname, Monthfieldname, Dayfieldname are the days of the year, month and day can be two-bit (MM) or a format (M),
This is not a separate test for each field (if you want to test, please use the previous general verification method in three fields of year/year, respectively), only the maximum value of the date is legal check;
4.2, date format verification (please note that this validation does not validate the validity of the date, and has not found a way to get the year date data from the format ^_^):
<input type= "text" name= "Datefieldname" value= "2003-01-03 21:31:00" >
<input type= "hidden" validatortype= "Date" fieldname= "Datefieldname"; format= "Yyyy-mm-dd HH:mm:ss" errorinfo= "Incorrect date!" >
Where the format only supports Y, M, D, H, M, s (other characters as non time characters)
4.3. List verification:
Verify that the list (checkbox, Redio, select) has at least one record selected (for select is primarily for multiple selections)
<input type= "checkbox" Name= "CheckBox1" >
<input type= "hidden" validatortype= checkbox "Fieldname=" CheckBox1 "errorinfo=" Please select at least one record! " >
Where validatortype can be checkbox, R, Select;
For a select form, if you want to select a record that cannot be the first article, use the following methods:
<select name= "Select1" emptyinfo= "Please select an option!" >
<option value= "" >== Please choose ==</option>
<option value= "1" >1</option>
<select>
4.4, Email verification:
<input type= "text" name= "email" >
<input type= "hidden" fieldname= "email" validatortype= "email" separator= "," errorinfo= "Incorrect email!" >
Where separator is optional, indicating the delimiter when entering multiple emails (no such option can be an address only)
4.5, add other JavaScript operation:
<script type= "Text/javascript" >
function functionname () {
Custom Methods
}
</script>
Add <input type= "hidden" to the form validatortype= "JavaScript" functionname= "functionname" > (at this point the Emptyinfo and other properties are invalid)
The JavaScript method specified in the Function property is invoked (requiring the method to return true or FALSE, and returning false will no longer validate the form or submit the form).
5. Disable a button before the form is submitted through validation (you can also disable other fields and cannot be in one domain with other validation), and do not require the button to be the last one in the form
<input type= "button" name= "Submit" validatortype= "Disable" >
6, do not verify the form
<input type= "hidden" name= "Validate" value= "0" functionname= "functionname" >
Submits a form when the validator field value is 0 o'clock without verifying the form, submitting the form directly or executing the specified function and returning True
functionname is optional

-->
<script type= "Text/javascript" >
function Getstringlength (str) {
var endvalue=0;
var sourcestr=new String (str);
var TempStr;
for (var strposition = 0; strposition < sourcestr.length; Strposition + +) {
Tempstr=sourcestr.charat (strposition);
if (tempstr.charcodeat (0) >255 | | tempstr.charcodeat (0) <0) {
endvalue=endvalue+2;
} else {
endvalue=endvalue+1;
}
}
return (Endvalue);
}
function Trim (str) {
if (str==null) return "";
if (str.length==0) return "";
var i=0,j=str.length-1,c;
for (; i<str.length;i++) {
C=str.charat (i);
if (c!= ') break;
}
for (; j>-1;j--) {
C=str.charat (j);
if (c!= ') break;
}
if (i>j) return "";
Return str.substring (i,j+1);
}
function Validatedate (date,format,alt) {
var Time=trim (Date.Value);
if (time== "") return;
var Reg=format;
var reg=reg.replace (/yyyy/, "[0-9]{4}");
var reg=reg.replace (/yy/, "[0-9]{2}");
var reg=reg.replace (/mm/, "((0[1-9)) |1[0-2]");
var reg=reg.replace (/m/, "(([1-9]) |1[0-2])");
var reg=reg.replace (/dd/, "(0[1-9)) | ( [1-2] [0-9]) | 30|31) ");
var reg=reg.replace (/d/, "[1-9]|[ 1-2][0-9]|30|31));
var reg=reg.replace (/hh/, "([[0-1][0-9]) |20|21|22|23)");
var reg=reg.replace (/h/, "([0-9]|1[0-9]|20|21|22|23)");
var reg=reg.replace (/mm/, "([0-5][0-9])");
var reg=reg.replace (/m/, "[0-9]| ( [1-5] [0-9]));
var reg=reg.replace (/ss/, "([0-5][0-9])");
var reg=reg.replace (/s/, "[0-9]| ( [1-5] [0-9]));
Reg=new RegExp ("^" +reg+ "$");
if (Reg.test (time) ==false) {//Verify that the format is legitimate
Alert (ALT);
Date.focus ();
return false;
}
return true;
}
function Validatedategroup (year,month,day,alt) {
var array=new array (31,28,31,30,31,30,31,31,30,31,30,31);
var y=parseint (Year.value);
var m=parseint (Month.value);
var d=parseint (Day.value);
var maxday=array[m-1];
if (m==2) {
if ((y%4==0&&y%100!=0) | | y%400==0) {
maxday=29;
}
}
if (d>maxday) {
Alert (ALT);
return false;
}
return true;
}
function Validatecheckbox (obj,alt) {
var Rs=false;
if (obj!=null) {
if (obj.length==null) {
return obj.checked;
}
for (i=0;i<obj.length;i++) {
if (obj[i].checked==true) {
return true;
}
}
}
Alert (ALT);
Return RS;
}
function Validateradio (obj,alt) {
var Rs=false;
if (obj!=null) {
if (obj.length==null) {
return obj.checked;
}
for (i=0;i<obj.length;i++) {
if (obj[i].checked==true) {
return true;
}
}
}
Alert (ALT);
Return RS;
}
function Validateselect (obj,alt) {
var Rs=false;
if (obj!=null) {
for (i=0;i<obj.options.length;i++) {
if (obj.options[i].selected==true) {
return true;
}
}
}
Alert (ALT);
Return RS;
}
function Validateemail (email,alt,separator) {
var Mail=trim (Email.value);
if (mail== "") return;
var em;
var myreg =/^[_a-z0-9]+@ ([_a-z0-9]+\.) +[a-z0-9]{2,3}$/;
if (separator==null) {
if (Myreg.test (email.value) ==false) {
Alert (ALT);
Email.focus ();
return false;
}
}
else{
Em=email.value.split (separator);
for (i=0;i<em.length;i++) {
Em[i]=em[i].trim ();
if (Em[i].length>0&&myreg.test (Em[i]) ==false) {
Alert (ALT);
Email.focus ();
return false;
}
}
}
return true;
}
function Validateform (theform) {//returns TRUE if validation passes
var disablelist=new Array ();
var field = theform.elements; Put all the elements in a form into an array
for (var i = 0; i < field.length; i++) {
var vali=theform.validate;
if (vali!=null) {
if (vali.value== "0") {
var fun=vali.functionname;
if (fun!=null) {
Return eval (fun+ "()");
}
else{
return true;
}
}
}

var Empty=false;
var Value=trim (Field[i].value);
if (value.length==0) {//IS null value
Empty=true;
}
var emptyinfo=field[i].emptyinfo;//null value Verification
if (emptyinfo!=null&&empty==true) {
alert (emptyinfo);
Field[i].focus ();
return false;
}
Maximum length verification for Var lengthinfo=field[i].lengthinfo;//
if (lengthinfo!=null&&getstringlength (value) >field[i].maxlength) {
alert (lengthinfo);
Field[i].focus ();
return false;
}

var Validatortype=field[i].validatortype;
if (validatortype!=null) {//other JavaScript
var rs=true;
if (validatortype== "JavaScript") {
Eval ("rs=" +field[i].functionname+ "()");
if (Rs==false) {
return false;
}
else{
Continue
}
}
else if (validatortype== "Disable") {//button for disable before submitting form
disablelist.length++;
Disablelist[disablelist.length-1]=field[i];
Continue
}
else if (validatortype== "Date") {
Rs=validatedate (Theform.elements (field[i].fieldname), field[i].format,field[i].errorinfo);
}
else if (validatortype== "Dategroup") {
Rs=validatedategroup (Theform.elements (field[i].year), theform.elements (Field[i].month), theForm.elements (field[i ].day), field[i].errorinfo);
}
else if (validatortype== "Checkbox") {
Rs=validatecheckbox (Theform.elements (field[i].fieldname), field[i].errorinfo);
}
else if (validatortype== "Radio") {
Rs=validateradio (Theform.elements (field[i].fieldname), field[i].errorinfo);
}
else if (validatortype== "Select") {
Rs=validateselect (Theform.elements (field[i].fieldname), field[i].errorinfo);
}
else if (validatortype== "Email") {
Rs=validateemail (Theform.elements (field[i].fieldname), field[i].errorinfo);
}
else{
Alert ("Authentication type is not supported, FieldName:" +field[i].name);
return false;
}
if (Rs==false) {
return false;
}
}
else{//General Verification
if (Empty==false) {
var v = field[i].validator; Gets its Validator property
if (!V) continue; If the property does not exist, ignore the current element
var reg=new RegExp (v);
if (Reg.test (field[i].value) ==false) {
alert (field[i].errorinfo);
Field[i].focus ();
return false;
}
}
}
}
for (i=0;i<disablelist.length;i++) {
Disablelist[i].disabled=true;
}
return true;
}
</script>



Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.