JavaScript-Customized Validation Framework example

Source: Internet
Author: User
Tags foreach error handling i18n trim

See the jquery verification framework, in the use of the time, in fact, is still very dizzy, very troublesome, the use of the time code is not concise, so have to get a own jquery verification framework of the plan, the basic principle is to input, select, textarea these three types of control to do calibration, Define a custom attribute inside as a test. In addition, the use of JS to do i18n internationalization, through the language of cookies, call different JS language packs, for their own development projects, enough to use, but also can be flexible expansion. Personal use should be good.

In order to test this validation framework, in fact, static HTML page is enough, but the habit of the problem, they built a simple dynamic Web project, followed by the source code download


1. The verification framework mainly uses jquery asynchronous objects to extend, that is, the use of jquery defered, so that the benefit of verification is that even if some of the validation is done in Ajax mode, combined with the jquery when function, can be batch checksum. The main code is as follows:

Function validator (errorhandle) {    this.errorHandle = errorHandle;  
   this.elements = ["Input", "select", "textarea"]; } validator.prototype = {        contructor :  Validator,         rules : {},          addrules : function (rulename, validfunction, errorfunction) {             this.rules[rulename] = {                      Validfunction : validfunction,                      errorfunction : errorfunction             &nbsP;};        &NBSP},                   eventfunction : function (item) {     
       var self = this;             $ (item). Die (). Live ("Blur",  function () {                 Self.validateitem (item);               
  });        &NBSP},                   bindingevent : function (divid) {     
       var self = this;            &nbsP             self.elements.foreach (function (element ) {                $ ("#"  +  divid). Find (Element). each (function (I, item) {                     self.eventfunction (item);                       
   });
            });                      &NBSP},                   Validatediv : function (divid) {             var dtdlist = [],                
 self = this;                               self.elements.foreach (function (element) {                      $ ("#"  + divid). Find (Element). each (function (I, item) {                         
Dtdlist.push ( self.validateitem (item)  );                     &NBSP});                          &NBsp;           });                               self.elements.foreach (function (element) {                      if  ("#"  + divid). Find (Element). length == 0) {                          var deferred = $.
Deferred ();                   
      deferred.resolve ();                   
      dtdlist.push (deferred);                      }                  
               });                           return $.when.apply (null, dtdlist). Fail (function () {                 if (Self.errorHandle)   {                     self.errorhandle.call (Null, divid);                                       }             });                      &NBSP},                   Validateitem : function (d) {            
var self = this;
            var ruleList = [];             for (var r in this.rules ) {                      if ( $ (D). is ("[ + r + ]")  ) {      
              rulelist.push (R);                 }              }              var dtd = $.
Deferred ();             var checked = function ( ) {                      if  ( ruleList.length >= 1 ) {                     var ok = 
Self.validate (D, rulelist[0]);                      ok.done (function () {                         if (rulelist.length >= 2) {                         
    self.validate (d, rulelist[1]);                          }             
            rulelist.shift ();                   
      checked ();                     &NBSP}). Fail (function () {                    &nbsP;    dtd.reject ();                   
  });                 } else  {                 
   dtd.resolve ();
                } ;                 //dtd.resolve (
);                 //return 
Dtd
            };
            checked ();
            return dtd;                      &NBSP},         validate : function (d, rule) {             var value = $ (D). Val (),                  attributeValue  = $ (d). attr (rule),                  f = this.rules[rule].validfunction,                  self = this;                                    var ok = f.call (null, d, value, 
AttributeValue);                           return ok.fail (function (item) {                 if ($ (item). Siblings ("[ValidationError]"). length !=  0 ) {                     $ (item). Siblings ("[ValidationError]"). Remove ();                                                }                  if (self.rules[rule].errorfunction) {                &Nbsp;    self.rules[rule].errorfunction (D, rule);
                }else {                      self.showerrormessage (D, rule);                                       }             &NBSP}). Done (function (item) {                 if ($ (item). Siblings ("[ValidationError]") .length != 0 ) {                     $ ( Item). Siblings ("[ValidationError]"). Remove ();                                                }             }
);        &NBSP},                   validationbyregx : function (D, VALUE, REGX) {             var dtd = $. Deferred (),             ok = regx.test (
Value);                       if (ok | |  $.trim (value)  ===  "") {                dtd.resolve (d);             } else {   
             dtd.reject (d);             }       
      return dtd.promise ();        &NBSP},                   /* Default error Handling method * *          Showerrormessage : function (item,rule) {          
  var msginfo = getjslocale ( $ (item) attr ("MsgId")  );             var ruleInfo = 
Getjslocale (  "Msg_"  + rule );             if ($ (item). Siblings ("span"). Find ("[msgid= ' Msg_" +  rule + "']"). length == 0) {                 var message = msginfo | |
 ruleInfo;                 $ (item). Parent (). Append ("<span validationerror><label msgid= ' Msg_"  + rule + "' >"  +  message +  "</label></span>");                            
  }         }; Add default rule Validator.prototype.addRules ("Required",  function (d, value,  AttributeValue) {    var dtd = $.
Deferred ();      var ok = ! ($.trim (value)  ==  ""  | |
 value == null);     if (OK) {        dtd.resolve (d);      } else {        dtd.reject (d);    
 }     return dtd.promise ();

}); Validator.prototype.addRules ("MaxLen",  function (d, value, attributevalue) {     var dtd = $.
Deferred ();
    var ok =  (Value.length <= attributevalue);     if (OK) {        dtd.resolve (d);      } else {        dtd.reject (d, 
AttributeValue);
    }     return dtd.promise ();     }, function (d, rule) {&NBSp;   if ($ (d). Siblings ("span"). Find ("[msgid= ' Msg_"  + rule +  "]"). length  == 0) {        var attributevalue = $ (d). attr
(rule);         var msginfo = getjslocale ( $ (d). attr ("
MsgId "), {length:attributevalue} );         var ruleinfo = getjslocale (  "Msg_"  +
 rule, {length:attributeValue} );         var message = msginfo | |
 ruleInfo;         $ (d). Parent (). Append ("<span validationError>< Label msgid= ' msg_ '  + rule +  '  errormsgparam= ' +attributevalue+ ' > '  +  message +  "</label></span>");                      }); Validator.prototype.addRules ("Minlen",  function (d, value, attributevalue) {     var dtd = $.
Deferred ();
    var ok =  (Value.length >= attributevalue);     if (OK) {        dtd.resolve (d);      } else {        dtd.reject (d, 
AttributeValue);
    }     return dtd.promise ();     }, function (d, rule) {    if ($ (d). Siblings ("span"). FIND (" [msgid= ' Msg_ '  + rule +  '] '. length == 0) {      
  var attributevalue = $ (d). attr (rule);         var msginfo = getjslocale ( $ (d). attr (" MsgId "),  {length:attributevalue} );         var ruleinfo = getjslocale (  "Msg_"  +
 rule, {length:attributeValue} );         var message = msginfo | |
 ruleInfo;         $ (d). Parent (). Append ("<span validationError>< Label msgid= ' msg_ '  + rule +  '  errormsgparam= ' +attributevalue+ ' > '  +  message +  "</label></span>");        
             }}); Validator.prototype.addRules ("url",  function (d, value, attributevalue) {     RETURN VALIDATOR.PROTOTYPE.VALIDATIONBYREGX (d, value, /^ (HT|F) TP (s)) \:\/\/) [A-za-z0-9]+\. [a-za-z0-9]+[\/=\?%\ -&_~ ' @[\]\ ': +!]
* ([^<>\ "\"]) *$/i);
}); Validator.prototype.adDrules ("Email",  function (d, value, attributevalue) {          RETURN VALIDATOR.PROTOTYPE.VALIDATIONBYREGX (d, value, /^ ([a-zA-Z0-9_\.\-]) +\@ ([a-zA-Z0-9 \-])+\.)
+ ([a-za-z0-9]{2,4}) +$/);
}); Validator.prototype.addRules ("中文版",  function (D, value, attributevalue) {          RETURN VALIDATOR.PROTOTYPE.VALIDATIONBYREGX (d, value, /^[
a-za-z0-9_\-]+$/); });

How do you validate HTML pages, using the following:
 

<div><h1> Custom Validation Framework test </h1></div>    <div>            <div id= "Required_valid_div" >             <input type= "Text"  required minlen= "3"  maxLen = "5"/>   <p />             English:<input type= "text"  required english maxlen= "/>   <p"  />            <input type= "text"   Required maxlen= "/>   <p />"             <input type= "Text"  url required />   <p  />            email: <input type= " Text " email&Nbsp;/>   <p />                        <select required>                 <option value= "" > Please Select </option>                < Option value= "1" > China </option>             </select>            <p />             <textarea required maxleng= "></" Textarea>  <p />             Custom error message: <input type= "text"  url required msgid= "Myurlerror"/>   <p  />                 </div>        <button onclick= "Javascript:validatordiv ();" > Validation </button>               < Button onclick= "JAVASCRIPT:LOADI18NCN ();" >Load  Chinese internationalization </button>        <button onclick= " Javascript:loadi18nen (); " >Load English i18N</button>            < /div>

JS Internationalization support

var Jslocale = {

msg_required: "Cannot be empty",

msg_maxlen: "Maximum length {{: length}}",

msg_minlen: "min. {: Length}" }.,

msg_url: "Illegal url",

msg_email: "Email is not legal",

msg_english: "Only allow input 0-9,a-z, A-Z",

Myurle Rror: "Custom error Hint: URL illegal oh", End

: ""

};

Test effect

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.