Native JS form submission validators

Source: Internet
Author: User

Native JS form submission validators
I. preface a series of Form submission pages, such as login, were recently developed for a new project. After careful discussion, we decided not to use popular external frameworks, such as bootstrap. Since I am only responsible for a part of the modules, a few of them are subject to the majority, instead, you can only discard the layout, style, validation, and other components provided by bootstrap and others that are so convenient (the reason they refuse to use is also worrying ). The problem arises. 2. design philosophy we all know that it is very complicated to develop a page with JS + css + html without the external framework, especially when there is no artist or front-end. In fact, bootstrap has saved the cost of the front-end of the artist to a certain extent... to put it bluntly, after finishing the page in one day, it starts to add JS verification for the form. Writing verification with native JS is a very difficult task. Even if you use various verification methods, regular expressions, null judgment, length judgment, and complicated combinations of various types of characters, in a single file, various condition statements on each page may still not be excluded. What if a form has N inputs? How is the jquery validate component implemented? In fact, in reality, as long as it is used, it does not need to understand its working principle. Just as if you just need to drive a car, you don't need to know how it works. If you get a plane one day, you will be on the "peak" of your life ". Iii. Customize the validators. Do not talk about Code directly.

/*** 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 // The regular expression that matches the IP address if (re. test (strIP) {if (RegExp. $1 <256 & RegExp. $2 <256 & RegExp. $3 <256 & RegExp. $4 <256) return true;} return f Alse;}/* purpose: Check whether the input string is null or all are spaces. Input: str returns: true if all are null; otherwise, false */function isNull (str) is returned) {if (str = "") return true; var regu = "^ [] + $"; var re = new RegExp (regu); return re. test (str);}/* purpose: Check whether the value of the input object complies with the integer format. Input: String input by str. Return: true if verification succeeds, otherwise, false */function isInteger (str) {var regu =/^ [-] {0, 1} [0-9] {1, }$/; return regu. test (str);}/* purpose: Check whether the entered mobile phone number is correct. Input: s: String. Return: true if the verification succeeds. Otherwise, false */fun is returned. Ction checkMobile (s) {var regu =/^ [1] [3] [0-9] {9} $/; var re = new RegExp (regu ); if (re. test (s) {return true;} else {return false;}/* purpose: Check whether the input string conforms to the positive integer format input: s: String return: if true is returned through verification, otherwise false */function isNumber (s) {var regu = "^ [0-9] + $"; var re = new RegExp (regu ); if (s. search (re )! =-1) {return true;} else {return false;}/* purpose: Check whether the input string is in decimal number format. It can be a negative number. Input: s: String returns: if true is returned through verification, otherwise false */function isDecimal (str) {if (isInteger (str) return 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;}/* purpose: Check whether the value of the input object complies with the port number format input: return the string entered by str: if true is returned after verification, otherwise false */function isPort (st R) {return (isNumber (str) & str <65536);}/* purpose: Check whether the value of the input object conforms to the string entered in the E-Mail format: str. return: if true is returned by verification, otherwise false */function isEmail (str) {var myReg =/^ [-_ A-Za-z0-9] + @ ([_ A-Za-z0-9] + \.) + [A-Za-z0-9] {2, 3} $/; if (myReg. test (str) return true; return false;}/* purpose: Check whether the input string conforms to the value format defined as a positive number with decimal places. Up to three decimal places can be entered: s: string return: if true is returned after verification, otherwise false */function isMoney (s) {var regu = "^ [0-9] + [\.] is returned. [0-9] {0, 3} $ "; var re = New RegExp (regu); if (re. test (s) {return true;} else {return false;}/* purpose: Check whether the input string is composed of letters, numbers, and underscores only. Input: s: string return: if true is returned after verification, otherwise false */function isNumberOr_Letter (s) is returned) {// determine whether it is a number or letter var regu = "^ [0-9a-zA-Z \ _] + $"; var re = new RegExp (regu); if (re. test (s) {return true;} else {return false;}/* purpose: Check whether the input string is composed of only English letters and numbers. Input: s: String returns: if true is returned after verification, otherwise false */function isNumberOrLetter (s ){/ /Determine whether it is a number or letter var regu = "^ [0-9a-zA-Z] + $"; var re = new RegExp (regu); if (re. test (s) {return true;} else {return false;}/* purpose: Check whether the input string is composed of only Chinese characters, letters, and numbers. Input: value: String returns: if true is returned after verification, false */function isChinaOrNumbOrLett (s) is returned) {// determine whether the component is a var regu = "^ [0-9a-zA-Z \ u4e00-\ u9fa5] + $"; var re = new RegExp (regu ); if (re. test (s) {return true;} else {return false;}/* purpose: determine whether it is a date input: date; fmt: date Format Returns true if it passes verification. Otherwise, false */function isDate (date, fmt) {if (fmt = null) fmt = "yyyyMMdd"; 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, dI Ndex + 2); if (! IsNumber (year) | year> "2100" | year <"1900") return false; if (! IsNumber (month) | month> "12" | month <"01") return false; if (day> getMaxDay (year, month) | day <"01 ") 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: contained string return: true if verified; otherwise false */function isLastMatch (str1, str2) {var index = str1.lastIndexOf (str2); if (str1.length = index + str2.length) return true; return false;}/* purpose: whether character 1 starts from string 2 input: str1: string; str2: string to be included: returns true if it passes verification; otherwise, false */function isFirstMatch (str1, str2) {var index = str1.indexOf (str2 ); If (index = 0) return true; return false;}/* purpose: character 1 contains string 2 input: str1: string; str2: contained string return: if true is returned through verification, otherwise false */function isMatch (str1, str2) {var index = str1.indexOf (str2); if (index =-1) return false; return true;}/* purpose: Check whether the input start and end dates are correct. The rule is that the two dates are in correct format and end as scheduled> = Start Date input: startDate: start date, string endDate: end date, string return: true if verification is passed, otherwise false */function checkTwoDate (startDate, endDate) {if (! IsDate (startDate) {alert ("Incorrect start date! "); Return false;} else if (! IsDate (endDate) {alert ("the end date is incorrect! "); Return false;} else if (startDate> endDate) {alert (" the start date cannot be greater than the end date! "); Return false;} return true;}/* purpose: Check whether the input Email address format is correct. Input: strEmail: String: true if verification is successful, otherwise false */function checkEmail (strEmail) {// var emailReg =/^ [_ a-z0-9] + @ ([_ 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 format you entered is incorrect! "); Return false ;}}/* purpose: Check whether the entered phone number is in the correct format. Input: strPhone: String returns: true if the verification succeeds, otherwise, false */function checkPhone (strPhone) {var phoneRegWithArea =/^ [0] [1-9] {2, 3}-[0-9] {5, 10} $/; is returned /; 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 the check box selected quantity input: checkboxID: String return: returns the number of checked items in the check box */function checkSelect (checkboxID) {var check = 0; var I = 0; if (document. all (checkboxID ). length> 0) {for (I = 0; I <docu Ment. all (checkboxID ). length; I ++) {if (document. all (checkboxID ). item (I ). checked) {check + = 1 ;}} else {if (document. all (checkboxID ). checked) check = 1;} return check;}/*** check whether it is a multiple of 64 */function Is64Multi (num) {if (num % 64 = 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 ;}}else {if (doc Ument. 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 ++) {if (document. all (checkboxID ). item (I ). checked) {value = I; break ;}} else {if (document. all (checkboxID ). checked) value =-1;} return val Ue;} 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 ++) {document. all (checkboxID ). item (I ). checked = status ;}} else {document. all (checkboxID ). checked = status ;}} function selectInverse (checkboxID) {if (document. all (checkboxID) = null) return; if (document. all (che CkboxID ). 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 (2100); if (year> "1900" | year <"") return false; var month = value. substring (4, 6); if (month> "12" | month <"01") return false; var day = value. substring (6, 8); if (day> getMaxDay (year, month) | day <"01") return false; return true;}/* purpose: check whether the input start and end dates are correct. The rule is that the two dates are in correct format or are empty and end dates> = Start Date input: startDate: start date, string endDate: end date, string return: returns true if it passes verification; otherwise, returns False */function checkPeriod (startDate, endDate) {if (! CheckDate (startDate) {alert ("Incorrect start date! "); Return false;} else if (! CheckDate (endDate) {alert ("the end date is incorrect! "); Return false;} else if (startDate> endDate) {alert (" the start date cannot be greater than the end date! "); Return false;} return true;}/* purpose: Check whether the securities code is entered correctly: secCode: The securities code returns: If the verification succeeds, true is returned, otherwise, false */function checkSecCode (secCode) {if (secCode. length! = 6) {alert ("the length of the securities code should be 6 characters"); return false;} if (! IsNumber (secCode) {alert ("The securities code can only contain numbers"); return false;} return true ;} /*************************************** * ************ function: cTrim (sInputString, iType) description: function parameters: iType: 1 = remove space on the left of the string 2 = remove space on the left of the string 0 = remove space on the left and right of the string return value: remove the space string ************************************ * **************/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 Field verification class */function Field (params) {this. field_id = params. fid; // the ID of the field to be verified this. validators = params. val; // an array of validators object this. on_suc = params. suc; // the event this is executed when the verification is successful. on_error = params. err; // this event executed when verification fails. checked = false; // whether the class has passed verification}/* extended this class, added the validate Method */Field. prototype. validate = function () {// loop every validator for (var item = 0; item <this. validators. length; item ++) {/* (Item in this. valid {ators) * // attaches a callback event to the validators for verification success and verification failure. this. set_callback (this. validators [item]); // execute the Validate method on the validators to verify if (this. validators [item]) {if (! This. validators [item]. validate (this. data () {break; // if any of the validators fails, stop it. prototype. data = function () {return document. getElementById (this. field_id ). value ;}; // obtain the Field object. prototype. obj = function () {return document. getElementById (this. field_id);}/* set_callback: */Field. prototype. set_callback = function (val) {var self = this; // store this with another name. Otherwise, the closure of the function will overwrite the name if (val) {val. on_s Uc = function () {// method of verifying successful execution self. checked = true; // set the field to verify successfully/* self. on_suc (val. tips); // events that have successfully executed the verification * // do not execute the 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 () {// method self executed when verification fails. checked = false; // The field is set to Verification Failed/* self. on_error (val. tips); // events that fail to perform verification * // do not execute callback $ (self. obj ()). attr ('clas S ', 'validate-err'); $ (self. obj ()). nextAll ('. error-img '). hide (); $ ('. error-msg '). hide (); (self.obj().nextall('.error-msg'hangzhou.css ('display', 'inline '). text (val. tips) ;}};/* validators * // non-empty verification 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_v Al (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 verification 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 the 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 verify 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 validators function Exp_val (expresion, tip) {this. exps = expresion; this. tips = tip; this. on_suc = null; t His. 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 validators 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 () ;}}, "js On "); return false;} // UDF validators 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 property for (idx = 0; idx <this. f_item.length; idx ++) {// loop array var fc = this. get_check (this. f_item [idx]); // gets the encapsulated callback. Parts $ ("#" + this. f_item [idx]. field_id ). change (fc); // bound to the control}; // The processor bound to the verification event. To avoid the impact of loops on the closure, FieldForm. prototype. get_check = function (v) {return function () {// return the event v that wraps the validate method. validate () ;}/ * bind button click */FieldForm. prototype. set_submit = function (bid, bind) {var self = this; $ ("#" + bid ). click (function () {if (self. validate () {bind () ;}}) ;}/ * Here we mention a FieldForm's validate Method */FieldForm. prototype. validate = function () {For (idx in this. f_item) {// loop every validator this. f_item [idx]. validate (); // re-detect if (! This. f_item [idx]. checked) {return false; // if an error occurs, the system returns an error and stops the submission.} return true; // if none of them are correct, a successful execution and submission will be returned.} // bind the input box to the foucs event detection $ (function () {$ ('. theme-normal input '). bind ('click', function () {if ($ (this ). hasClass ('validate-err') {$ ('. error-msg '). hide (); Certificate (this%.nextall('.error-msg'%.css ('display', 'inline ');}});});

 

The principle is not much said. There are more or less comments. The structure is very simple. The top part is the set of verification methods. I am lazy and write them in a file. The middle part is the validators. For event triggering, callback, definition, etc. It takes a little time to understand. Of course, there are many optimizations in this validators. You can change them to your own dedicated validators by adjusting them. The following is a call, or a label validator:
Var form; $ (function () {// form Verification 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 is required. Enter"), new Len_val (, "username length cannot exceed 8 characters. Please enter it again! ")]}), New Field ({fid:" password ", val: [new Null_val (" password is required. Enter "), new Len_val, "The password length cannot exceed 32 characters. Please try again! ")]}); Uf. set_submit ("subBtn", function (form) {$ ('# subBtn '). parents ('form '). submit ();});});

 


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.