Native JS form submission Validator

Source: Internet
Author: User

First, preface

Recently in the development of a new project, we need to do a series of landing and other Forms submission page. After a "thoughtful" discussion, we decided not to use the externally popular framework, such as Bootstrap, because I was responsible for the module

is only part of it, so a few obey the majority, helpless can only abandon the layout, style and validation of bootstrap and other components such as convenient, (they refuse to use the reason is also very provincial).

Then the problem comes.

Second, the design concept

As we all know, it is very complicated to use js+css+html to develop a page without the external frame, especially in the case of no art, foreground. In fact, bootstrap to a certain extent for the company to save the art of the front desk expenses ...

Less nonsense, 1 days after the page is finished, start adding JS validation to the form. With the native JS write verification is a very difficult thing, even if the various verification methods, regular expressions, for empty judgment, length judgment, complex types of character combination judgment, etc., concentrated in a file, still may not be able to exclude each page of the various conditional statements, in case a form n input?

And the jquery validate component is how to achieve, in fact, in reality, as long as it will be used on the line without understanding its working principle. As long as you can drive a car is enough, do not have to understand how the car is achieved, then when you will fly a day, then you boarded the "peak" of life.

Iii. Custom Validator

Nonsense not much to say directly on the code

  

/** * Created by Sicd 2015-5-29. */$ (function () {}), var suc_img= ' <i class= ' error-img ' ></i> '; var err_tag= ' <span class= ' error-msg ' id= ' Error-msg "style=" Display:block; "    ></span> '; function IsIP (StrIP) {if (IsNull (StrIP)) return false; var re=/^ (\d+) \. (\d+) \. (\d+) \. (\d+) $/g//match the regular expression of the IP address if (re.test (StrIP)) {if (regexp.$1 <256 && regexp.$2<256 && Reg    exp.$3<256 && regexp.$4<256) return true; } return false;}    /* Purpose: Check whether the input string is empty or all spaces are input: str Returns TRUE if ALL is NULL, otherwise returns false */function IsNull (str) {if (str = = = "") return "    var Regu = "^[]+$";    var re = new RegExp (Regu); return Re.test (str);} /* Purpose: Check that the value of the input object conforms to the integer format input: The string returned by the str input: True if verified, returns false */function Isinteger (str) {var regu =/^[-]{0,1}[0-9]{    1,}$/; return Regu.test (str);}    /* Use: Check that the input phone number is entered correctly: S: String returns: True if verified, returns false */function Checkmobile (s) {var regu =/^[1][3][0-9]{9}$/;    var re = new RegExp (Regu); if (re. Test (s)) {return true;    }else{return false;    }}/* use: Check that the input string conforms to the positive integer format input: s: String returns: True if verified, returns false */function Isnumber (s) {var regu = "^[0-9]+$";    var re = new RegExp (Regu);    if (S.search (re)! =-1) {return true;    } else {return false; }}/* use: Check whether the input string is a numeric format with decimals, can be negative input: s: String returns: False if True is returned by validation, */function Isdecimal (str) {if (Isinteger (str)) r    Eturn true; var re =/^[-]{0,1} (\d+) [\.]    + (\d+) $/;        if (Re.test (str)) {if (regexp.$1==0&&regexp.$2==0) return false;    return true;    } else {return false; }}/* use: Check that the value of the input object conforms to the port number format input: The string returned by str input: Returns TRUE if verified, otherwise false */function isport (str) {return (Isnumber (str) & & str<65536);} /* Purpose: Check whether the value of the input object conforms to the e-mail format input: The string returned by str input: If TRUE is returned by validation, false */function Isemail (str) {var myreg =/^[-_a-za-z0- 9][email protected] ([_a-za-z0-9]+\.)    +[a-za-z0-9]{2,3}$/;    if (Myreg.test (str)) return true; return false;} /* Use: Check input wordCharacter string is defined as a positive number with decimals, up to three digits after the decimal point: S: String returns: True if verified, returns false */function Ismoney (s) {var regu = "^[0-9]+[\.] [0-9]    {0,3}$ ";    var re = new RegExp (Regu);    if (Re.test (s)) {return true;    } else {return false; }}/* use: Check that the input string is composed only of English letters and numbers and underscores input: s: string return: True if verified, return false */function Isnumberor_letter (s) {//To determine if it is a number or letter Va    R Regu = "^[0-9a-za-z\_]+$";    var re = new RegExp (Regu);    if (Re.test (s)) {return true;    }else{return false; }}/* use: Check that the input string is only composed of English letters and numbers input: s: string return: True if verified, return false */function Isnumberorletter (s) {//Determine whether it is a numeric or letter Var reg    u = "^[0-9a-za-z]+$";    var re = new RegExp (Regu);    if (Re.test (s)) {return true;    }else{return false; }}/* use: Check that the input string is only entered by Chinese characters, letters, and Numbers: value: String return: True if verified, return false */function Ischinaornumborlett (s) {//To determine if it is a Chinese character, a letter    , the number consists of var Regu = "^[0-9a-za-z\u4e00-\u9fa5]+$";    var re = new RegExp (Regu);    if (Re.test (s)) {return true;    }else{    return false; }}/* use: Determine if it is a date input: date: Dates; FMT: Date format returns: False if True is returned by validation, */function isDate (date, FMT) {if (fmt==null) fmt= "yyyy    MMdd ";    var yindex = fmt.indexof ("yyyy");    if (yindex==-1) return false;    var year = date.substring (yindex,yindex+4);    var mindex = Fmt.indexof ("MM");    if (mindex==-1) return false;    var month = date.substring (mindex,mindex+2);    var dindex = Fmt.indexof ("dd");    if (dindex==-1) return false;    var day = date.substring (dindex,dindex+2); if (!isnumber (year) | | Year> "2100" | |    year< "1900") return false; if (!isnumber (month) | | Month> "12" | |    month< "") return false;    if (Day>getmaxday (year,month) | | day< "") return false; return true;} function Getmaxday (year,month) {if (month==4| | month==6| | month==9| |    month==11) return "30";        if (month==2) if (year%4==0&&year%100!=0 | | year%400==0) return "29";    else return "28"; return "31";} /* Purpose: Whether character 1 ends with string 2 input: str1: string; sTR2: The contained string returns: False if True is returned by validation */function Islastmatch (str1,str2) {var index = str1.lastindexof (STR2);    if (str1.length==index+str2.length) return true; return false;} /* Purpose: Character 1 is entered as String 2: str1: string; str2: String returned: True if verified, returns false */function Isfirstmatch (STR1,STR2) {var index = s    Tr1.indexof (STR2);    if (index==0) return true; return false;} /* Use: Character 1 is a string containing 2 input: str1: string; str2: String returned: True if verified, returns false */function IsMatch (STR1,STR2) {var index = Str1.ind    Exof (STR2);    if (index==-1) return false; return true;} /* Purpose: Check that the input start and end date is correct, that the rule is formatted correctly for two dates, and that it ends as expected >= Starting date input: StartDate: Start date, string endDate: End as expected, string return: False If True is returned by validation */        function Checktwodate (startdate,enddate) {if (!isdate (startdate)) {alert ("Start date incorrect!");    return false;        } else if (!isdate (endDate)) {alert ("End date incorrect!");    return false;        } else if (StartDate > EndDate) {alert ("The start date cannot be greater than the end date!");    return false; } return true; /* Use: Check the input emailWhether the mailbox format is entered correctly: Stremail: string return: True if verified, return false */function Checkemail (stremail) {//var Emailreg =/^[_a-z0-9][email  protected] ([_a-z0-9]+\.)    +[a-z0-9]{2,3}$/; var Emailreg =/^[\w-]+ (\.[ \w-]+) *@[\w-]+ (\.[    \w-]+) +$/;    if (Emailreg.test (Stremail)) {return true; }else{alert ("The email address you entered is not in the correct format!)        ");    return false; }}/* use: Check that the input phone number format is entered correctly: Strphone: string return: True if verified, return false */function Checkphone (strphone) {var phoneregwit    Harea =/^[0][1-9]{2,3}-[0-9]{5,10}$/;    var phoneregnoarea =/^[1-9]{1}[0-9]{5,8}$/;    var prompt = "The phone number you entered is incorrect!"        if (Strphone.length > 9) {if (Phoneregwitharea.test (Strphone)) {return true;            }else{alert (prompt);        return false;        }}else{if (Phoneregnoarea.test (Strphone)) {return true;            }else{alert (prompt);        return false; }}}/* Purpose: Check check box is selected number of input: Checkboxid: String return: Returns the number of selected in this check box */function cheCkselect (CHECKBOXID) {var check = 0;    var i=0;            if (document.all (CHECKBOXID). length > 0) {for (i=0; I<document.all (CHECKBOXID). length; i++) {            if (document.all (CHECKBOXID). Item (i). checked) {check + = 1;    }}}else{if (document.all (CHECKBOXID). checked) check = 1; } return check;} /* * Check if it is a multiple of 64 */function is64multi (num) {if (num% = = 0) {return true;} Else{return false;}}    function GetTotalBytes (Varfield) {if (Varfield = = null) return-1;    var totalcount = 0;  for (i = 0; i< varField.value.length; i++) {if (VarField.value.charCodeAt (i) > 127) TotalCount + =        2;    else totalcount++; } return totalcount;}    function Getfirstselectedvalue (CHECKBOXID) {var value = null;    var i=0; if (document.all (CHECKBOXID). length > 0) {for (i=0; I<document.all (CHECKBOXID). length; i++) {if (Document.all (Checkboxid). Item (i). checked) {value = document.all (CHECKBOXID). Item (i). value;            Break    }}} and else {if (document.all (CHECKBOXID). Checked) value = document.all (CHECKBOXID). value; } return value;    function Getfirstselectedindex (CHECKBOXID) {var value =-2;    var i=0; if (document.all (CHECKBOXID). length > 0) {for (i=0; I<document.all (CHECKBOXID). length; i++) {i                F (document.all (CHECKBOXID). Item (i). checked) {value = i;            Break    }}} and else {if (document.all (CHECKBOXID). Checked) value =-1; } return value;    function SelectAll (checkboxid,status) {if (document.all (checkboxid) = = null) return; if (document.all (CHECKBOXID). length > 0) {for (i=0; I<document.all (CHECKBOXID). length; i++) {do        Cument.all (CHECKBOXID). Item (i). checked = status; }} else {document.all(CHECKBOXID). checked = status;    }}function Selectinverse (CHECKBOXID) {if (document.all (checkboxid) = = null) return;            if (document.all (CHECKBOXID). length > 0) {for (i=0; I<document.all (CHECKBOXID). length; i++) {        document.all (CHECKBOXID). Item (i). Checked =!document.all (CHECKBOXID). Item (i). checked;    }} else {document.all (CHECKBOXID). Checked =!document.all (CHECKBOXID). checked;    }}function Checkdate (value) {if (value== ') return true;    if (value.length!=8 | |!isnumber (value)) return false;    var year = value.substring (0,4);    if (year> "2100" | | | year< "1900") return false;    var month = value.substring (4,6);    if (month> "| | | month<") return false;    var day = value.substring (6,8);    if (Day>getmaxday (year,month) | | day< "") return false; return true;} /* Purpose: Check that the input start and end date is correct, the rule is formatted correctly for two dates, or both are empty and the ending date >= from: startdate: Start date, string endDate: End Date, string return: If True is returned by validation, Otherwise returns false */functiOn Checkperiod (startdate,enddate) {if (!checkdate (startdate)) {alert ("Start date incorrect!");    return false;        } else if (!checkdate (endDate)) {alert ("End date incorrect!");    return false;        } else if (StartDate > EndDate) {alert ("The start date cannot be greater than the end date!");    return false; } return true; /* Use: Check that the security code is entered correctly: Seccode: Security Code return: True if verified, returns false */function Checkseccode (seccode) {if (Seccode.length! =        6) {alert ("The length of the security code should be 6 bits");    return false;        } if (!isnumber (Seccode)) {alert ("Security code can only contain numbers");    return false; } return true; /**************************************************** Function:ctrim (Sinputstring,itype) Description: A function of string de-whitespace parameters:itype:1= Remove the space to the left of the string 2= Remove the space to the left of the string 0= Remove the space to the left and right of the string return value: The string that removes the space **********************************    /function Ctrim (sinputstring,itype) {var stmpstr = ';    var i =-1; if (IType = = 0 | | iType = = 1) {while (stmpstr = = ") {++i;            Stmpstr = Sinputstring.substr (i, 1);    } sinputstring = sinputstring.substring (i);        } if (IType = = 0 | | iType = = 2) {stmpstr = ';        i = sinputstring.length;            while (stmpstr = = ") {-I.;        Stmpstr = Sinputstring.substr (i, 1);    } sinputstring = sinputstring.substring (0, i + 1); } return sinputstring;}    function Checklength (str, Lesslen, Morelen) {var strLen = this.length (str);    if (Lesslen! = "") {if (StrLen < Lesslen) return false;     }}/* describes the class of field validation */function field (params) {this.field_id=params.fid;   The ID of the field to validate This.validators=params.val;       An array of validator objects this.on_suc=params.suc;     The event This.on_error=params.err executed when the validation was successful;           The event that is executed when validation fails This.checked=false; Whether to extend this class by validating}/*, add the Validate method */field.prototype.validate=function () {//Loop each validator for (Var Item=0;item<this.valida       tors.length;item++) {/*for (item in this.valid{ators) */ A callback event This.set_callback (This.validators[item]) that attaches validation success and validation failures to the validator;            Executes the Validate method on the validator to verify compliance with the rule if (This.validators[item]) {if (!this.validators[item].validate (This.data ())) { Break Once any validator fails stop}}}};//gets the field value method Field.prototype.data=function () {return document.getElementById (this . field_id). value;};/ /Gets the object of the field field.prototype.obj=function () {return document.getElementById (this.field_id);}              /* The method for setting the validator callback function is set_callback as follows: */field.prototype.set_callback=function (val) {var self=this;      Change a name to store this, otherwise the function's closure will overwrite the name if (val) {val.on_suc=function () {//) {//Verify the successful execution of the method self.checked=true;  Set the field to validation success/*SELF.ON_SUC (val.tips);        Perform validation Successful event *//Do not execute callback $ (self.obj ()). attr (' class ', ' validate-suc ');        $ (Self.obj ()). Nextall ('. error-img '). Show ();    $ (Self.obj ()). Nextall ('. Error-msg '). Hide (). text (val.tips);    };     Val.on_error=function () {////validation fails when the method is executed self.checked=false;The field is set to validation failed/*self.on_error (val.tips);//event validation failed *///Do not execute callback $ (self.obj ()). attr (' class ', ' Validate-err '        );        $ (Self.obj ()). Nextall ('. error-img '). Hide ();        $ ('. Error-msg '). Hide ();    $ (Self.obj ()). Nextall ('. error-msg '). CSS (' Display ', ' inline '). Text (val.tips);    }}};/* Validator *///non-null validation function Null_val (tip) {this.tips = tip;    This.on_suc=null; This.on_error=null;}        Null_val.prototype.validate=function (FD) {if (IsNull (FD)) {this.on_error ();    return false;    } this.on_suc (); return true;}    Length verification function len_val (min_l,max_l,tip) {this.min_v=min_l;    this.max_v=max_l;    This.tips=tip;    This.on_suc=null; This.on_error=null;} Len_val.prototype.validate=function (FD) {if (fd.length<this.min_v| |        Fd.length>this.max_v) {this.on_error ();    return false;    } this.on_suc (); return true;}    Positive integer number validation function Posiinteg_val (tip) {this.tips=tip;    This.on_suc=null; This.on_error=null;} PosiInteg_val.prototype.validate = function (FD) {if (!isnumber (FD)) {this.on_error ();    return false;    } this.on_suc (); return true;}    Whether it is a multiple of 64 function is64multiple (tip) {this.tips=tip;    This.on_suc=null; This.on_error=null;} Is64Multiple.prototype.validate = function (FD) {if (!        Is64multi (FD)) {this.on_error ();    return false;    } this.on_suc (); return true;}        Select whether to choose to validate Select_isselected.prototype.validate=function (FD) {if (fd = =-1) {this.on_error ();    return false;    } this.on_suc (); return true;}    function select_isselected (tip) {this.tips=tip;    This.on_suc=null; This.on_error=null;}    Regular Expression Validator function Exp_val (expresion,tip) {this.exps=expresion;    This.tips=tip;    This.on_suc=null; This.on_error=null;}        Exp_val.prototype.validate=function (FD) {if (!FD) {this.on_suc ();    return true;        } if (This.exps.test (FD)) {this.on_suc ();    return true;        }else{This.on_error ();   return false; }}//Remote Validator Function Remote_val (url,tip) {this.p_url=url;    This.tips=tip;    This.on_suc=null; This.on_error=null;}    Remote_val.prototype.validate=function (FD) {var self=this;                $.post (THIS.P_URL,{F:FD}, function (data) {if (data.rs) {self.on_suc ();            Return            }else{Self.on_error ();    }}, "JSON"); return false;}    The Custom Function Validator function Man_val (tip,func) {this.tips=tip;    This.val_func=func;    This.on_suc=null; This.on_error=null;}    Man_val.prototype.validate=function (FD) {if (This.val_func (FD)) {this.on_suc ();    }else{This.on_error ();                             }}function fieldform (items) {this.f_item=items; Copy the field validation object array to the attribute for (idx=0;idx<this.f_item.length;idx++) {//loop array var fc=this.get_check (This.f_item[idx]   ); Gets the encapsulated callback event $ ("#" +this.f_item[idx].field_id). Change (FC); Binds the processor to the}};//binding validation event on the control, in order to avoid the effect of the loop on the closure FieldForm.prototype.get_cHeck=function (v) {return function () {//return} wraps the event v.validate () that calls the Validate method;    }}/* bind button Click*/fieldform.prototype.set_submit=function (bid,bind) {var self=this;            $ ("#" +bid). Click (function () {if (Self.validate ()) {bind ()}; }        }    );}         /* Here refers to a fieldform Validate method */fieldform.prototype.validate=function () {for (idx in This.f_item) {//Loop each validator     This.f_item[idx].validate ();                Again detect if (!this.f_item[idx].checked) {return false;                         If the error returns a failure, Block commit}} return true; One is right. Returns the successfully executed commit}//bound input box Foucs event detection $ (function () {$ ('. Theme-normal input '). Bind (' click ', function () {if ($ (this). h            Asclass (' Validate-err ')) {$ ('. Error-msg '). Hide ();        $ (this). Nextall ('. error-msg '). CSS (' Display ', ' inline '); }    });});

Principle is not much to say, more or less have comments, structure is very simple, the top part is the verification method set, I lazy directly written in a file, the middle part is the validator, about the event trigger, callback, definition, etc.,

Take a little bit of time to read it. Of course, there are many optimizations for this validator, which can be adjusted to match your own dedicated authenticator.

The following is a call, or a tag validator, that is given:

  

var form;    $ (function () {        //form validation        var uf = new Fieldform ([        new Field ({fid: "Captcha", Val: [New Null_val ("Verification code is required, enter")] }),        new Field ({fid: "username", Val: [New Null_val ("username required, enter"), new Len_val (1, 8, "username cannot be longer than 8 bits, please re-enter!) ")]}),        new Field ({fid:" Password ", Val: [New Null_val (" Password is required, please enter "), new Len_val (1, 32," password length cannot exceed 32 bits, please re-enter!) ")]})]);    Uf.set_submit ("Subbtn", function (form) {        $ (' #subBtn '). Parents (' form '). Submit ();    });    });        

Effect

  

Where the style is written by myself, when input (including the drop-down box) value changes to verify (can adjust the validator, change the trigger form), submit trigger validation, when input gets focus

If the previous validation does not pass, the prompt box pops up.

Iv. Summary

Very simple, one afternoon can understand and adjust freely, because I lazy, did not show CSS-related code files, if interested, you can take these things to extract or do integration

It is made into components and made into a date control, so as to facilitate portability and application.

  

Tip: (cue box and other styles if you need to leave a message)

Native JS form submission Validator

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.