dojox/validate是一个包含了很多通用验证逻辑的工具集,比如检查email地址的合法性,邮政编码,电话号码等等。dojox/validate在新版本中已被弃用。
dojox/validate可以直接使用一些基本的功能:
validate.isInRange(test,options); validate.isNumberFormat(test,options); validate.isText(test,options); validate.isValidLuhn(test);
这里的每一个方法(除了isValidLuhn)都可以接受一个额外的配置参数optons,来指定额外的验证信息。比如:isNumberFormat方法可以指定数字的格式,例如:
vartest=validate.isNumberFormat(someNum,{format:"(###)###-####"});
格式化信息也可以以数组的方式指定,例如:
vartest=validate.isNumberFormat(someNum,{ format:["#####","###-##","#####"] });
除了上面的4个方法,dojox/validate还包含了很多其他的验证规则供你使用,例如:
validate.creditCard validate.isbn validate.web
和其他很多dojo模块不太一样,require一个validate模块不会创建新的独立对象,而是为dojox/validate模块增加更多的方法。例如,如果你的应用需要web相关的一些验证,可以用如下代码:
require(["dojox/validate/web"],function(validate){ validate.isEmailAddress(someAddress); });
最后,还有2个模块专门用于北美和加拿大相关的格式信息:dojox/validate/us和dojox/validate/ca。这些模块提供了国家相关的电话号码,邮政编码,社保号等信息的验证。
如果你的应用使用直接的HTML表单Form,dojox/validate提供了一个称之为check的模块,可以让你去定义一个验证逻辑的配置文件(profile),你可以用这个配置文件来确保表单中的输入值都是有效的。这个配置文件是一个javascript对象,功能相当强大,它提供了filter来过滤表单值,定义了哪些表单域是必须的,定义了表单域的相互依赖(比如一个表单域依赖于另外一个表单域),定义了值的规则,以及需要确认的表单域(例如:密码值通常要输入两遍以确认)。
<!DOCTYPEHTML> <htmllang="en"> <head> <Metacharset="utf-8"> <title>Demo:DojoXValidateandHTMLForms</title> <linkrel="stylesheet"href="dijit/themes/claro/claro.css"> <styletype="text/css"> label{ display:inline-block; width:140px; } </style> </head> <bodyclass="claro"> <h1>Demo:DojoXValidateandHTMLForms</h1> <pstyle="font-size:x-small"> *是必填字段. </p> <form> <div> <labelfor="firstName">FirstName*</label> <inputtype="text"name="firstName"id="firstName"value=""/> </div> <div> <labelfor="lastName">LastName*</label> <inputtype="text"name="lastName"id="lastName"value=""/> </div> <div> <labelfor="email">EmailAddress*</label> <inputtype="text"name="email"id="email"value=""/> </div> <div> <labelfor="emailConfirm">ConfirmEmail*</label> <inputtype="text"name="emailConfirm"id="emailConfirm"value=""/> </div> <div> <labelfor="password">Password*</label> <inputtype="password"name="password"id="password"value=""/> </div> <div> <labelfor="password2">ConfirmPassword*</label> <inputtype="password"name="password2"id="password2"value=""/> </div> <div> <labelfor="phone">Phone</label> <inputtype="text"name="phone"id="phone"value=""/> </div> <inputtype="submit"value="Post!"/> </form> <h3>Formvalidationresults</h3> <divid="result"style="border-top:1pxsolid#999;"></div> <!--loaddojoandprovideconfigviadataattribute--> <scriptsrc="dojo/dojo.js"data-dojo-config="async:true,parSEOnLoad:true"></script> <script> require(["dojo/dom","dojo/_base/array","dojo/_base/event","dojo/query","dojox/validate/web","dojox/validate/us","dojox/validate/check","dojo/domReady!"],function(dom,baseArray,baseEvent,query,validate){ functiondoCheck(form){ varresults=validate.check(form,profile),r=dom.byId("result"); //通过验证 if(results.isSuccessful()){ // everythingpassed,logittotheresultdiv r.innerHTML="Everythingpassedvalidation!"; }else{ vars=""; //字段缺失 varmissing=results.getMissing(); if(missing.length){ s+='<h4>Thefollowingfieldsaremissing:</h4>' +'<ol>'; baseArray.forEach(missing,function(field){ s+='<li>'+field+'</li>'; }); s+='</ol>'; } //输入字段无效 varinvalid=results.getInvalid(); if(invalid.length){ s+='<h4>Thefollowingfieldsareinvalid:</h4>' +'<ol>'; baseArray.forEach(invalid,function(field){ s+='<li>'+field+'</li>'; }); s+='</ol>'; } r.innerHTML=s; } } // waituntilafterourrequiresareactuallyloaded. profile={ trim:["firstName","lastName"],required:["firstName","lastName","email","emailConfirm","password","password2"],constraints:{ firstName: validate.isText,lastName: validate.isText,password: validate.isText,password2: validate.isText,email: [validate.isEmailAddress,false,true],emailConfirm:[validate.isEmailAddress,phone: validate.us.isPhoneNumber },confirm:{ "emailConfirm":"email","password2":"password" } }; // setuptheformhandler. varf=query("form")[0]; f.onsubmit=function(e){ baseEvent.stop(e); doCheck(f); }; }); </script> </body> </html>
输出结果:
在基于Dijit的表单里使用dojox/validate
当然,你也可以结合dojox/validate和dijit一起使用,特别是dijit的ValidationTextBox。这里的关键是ValidationTextBox的validator方法。
<!DOCTYPEHTML> <htmllang="en"> <head> <Metacharset="utf-8"> <title>Demo:DojoXValidationwithDijitForms</title> <linkrel="stylesheet"href="dijit/themes/claro/claro.css"> <scriptsrc="dojo/dojo.js"data-dojo-config="async:true,parSEOnLoad:true"></script> <styletype="text/css"> label{ display:inline-block; width:140px; } </style> <script> require(["dojo/parser",/*dojox/validateresources*/ "dojox/validate/us",/*basicdijitclasses*/ "dijit/form/CheckBox","dijit/form/Textarea","dijit/form/FilteringSelect","dijit/form/TextBox","dijit/form/ValidationTextBox","dijit/form/DateTextBox","dijit/form/TimeTextBox","dijit/form/Button","dijit/form/RadioButton","dijit/form/Form",/*basicdojoxclasses*/ "dojox/form/BusyButton","dojox/form/CheckedMultiSelect","dojo/domReady!"]); </script> </head> <bodyclass="claro"> <h1>Demo:DojoXValidationwithDijitForms</h1> <pstyle="font-size:x-small"> *是必填字段. </p> <formdata-dojo-type="dijit/form/Form"method="post"> <scripttype="dojo/method"event="onSubmit"> if(this.validate()){ returnconfirm('Formisvalid,pressOKtosubmit'); }else{ alert('Formcontainsinvaliddata.Pleasecorrectfirst'); returnfalse; } returntrue; </script> <div> <labelfor="firstName"><strong>FirstName*:</strong></label> <inputtype="text"required="true"name="firstName"id="firstName"placeholder="YourName" data-dojo-type="dijit/form/ValidationTextBox"missingMessage="Ooops!Youforgotyourfirstname!"/> </div> <div> <labelfor="website"><strong>Website*:</strong></label> <inputtype="text"required="true"name="website"id="website"placeholder="YourWebsite" data-dojo-type="dijit/form/ValidationTextBox"validator="dojox.validate.isUrl"/> </div> <div> <labelfor="email"><strong>Email*:</strong></label> <inputtype="text"required="true"name="email"id="email"data-dojo-type="dijit/form/ValidationTextBox" validator="dojox.validate.isEmailAddress"/> </div> <div> <labelfor="bday"><strong>DateofBirth*:</strong></label> <inputtype="text"required="true"name="bday"id="bday"data-dojo-type="dijit/form/DateTextBox"value="7/5/1983"/> </div> <div> <labelfor="color"><strong>FavoriteColor:</strong></label> <selectname="color"id="color"data-dojo-type="dijit/form/FilteringSelect"> <optionvalue="">SelectaColor</option> <optionvalue="Red">Red</option> <optionvalue="Green">Green</option> <optionvalue="Blue">Blue</option> </select> </div> <div> <labelfor="toolkits"><strong>FavoriteToolkits:</strong></label> <selectname="toolkits"id="toolkits"data-dojo-type="dojox/form/CheckedMultiSelect"multiple="multiple"style="width:200px;"> <optionvalue="Dojo"selected="selected">DojoToolkit</option> <optionvalue="Moo"selected="selected">MooTools</option> <optionvalue="Prototype">Prototype</option> <optionvalue="YUI">YUI</option> <optionvalue="jQuery"disabled>jQuery</option> </select> </div> <div> <labelfor="MyCheckBox"><strong>SendEmails?:</strong></label> <inputid="MyCheckBox"name="MyCheckBox"data-dojo-type="dijit/form/CheckBox"checked="false"/> </div> <div> <label><strong>EmailFormat:</strong></label> <inputtype="radio"id="radio1"name="format"checked="checked"data-dojo-type="dijit/form/RadioButton"/>HTML <inputtype="radio"id="radio2"name="format"data-dojo-type="dijit/form/RadioButton"/>Text </div> <inputtype="submit"value="SubmitForm"label="SubmitForm"id="submitButton"data-dojo-type="dijit/form/Button"/> </form> </body> </html>
输出结果:
原文链接:https://www.f2er.com/dojo/291104.html