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方法可以指定数字的格式,例如:
var test = validate.isNumberFormat(someNum, { format: "(###) ###-####" });
格式化信息也可以以数组的方式指定,例如:
var test = 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来过滤表单值,定义了哪些表单域是必须的,定义了表单域的相互依赖(比如一个表单域依赖于另外一个表单域),定义了值的规则,以及需要确认的表单域(例如:密码值通常要输入两遍以确认)。
<!DOCTYPE HTML> <html lang="en"> <head> <meta charset="utf-8"> <title>Demo: DojoX Validate and HTML Forms</title> <link rel="stylesheet" href="dijit/themes/claro/claro.css"> <style type="text/css"> label { display: inline-block; width: 140px; } </style> </head> <body class="claro"> <h1>Demo: DojoX Validate and HTML Forms</h1> <p style="font-size: x-small"> * 是必填字段. </p> <form> <div> <label for="firstName">First Name*</label> <input type="text" name="firstName" id="firstName" value="" /> </div> <div> <label for="lastName">Last Name*</label> <input type="text" name="lastName" id="lastName" value="" /> </div> <div> <label for="email">Email Address*</label> <input type="text" name="email" id="email" value="" /> </div> <div> <label for="emailConfirm">Confirm Email*</label> <input type="text" name="emailConfirm" id="emailConfirm" value="" /> </div> <div> <label for="password">Password*</label> <input type="password" name="password" id="password" value="" /> </div> <div> <label for="password2">Confirm Password*</label> <input type="password" name="password2" id="password2" value="" /> </div> <div> <label for="phone">Phone</label> <input type="text" name="phone" id="phone" value="" /> </div> <input type="submit" value="Post!" /> </form> <h3>Form validation results</h3> <div id="result" style="border-top:1px solid #999;"></div> <!-- load dojo and provide config via data attribute --> <script src="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) { function doCheck(form){ var results = validate.check(form, profile), r = dom.byId("result"); //通过验证 if(results.isSuccessful()){ // everything passed, log it to the result div r.innerHTML = "Everything passed validation!"; } else { var s = ""; //字段缺失 var missing = results.getMissing(); if(missing.length){ s += '<h4>The following fields are missing:</h4>' + '<ol>'; baseArray.forEach(missing, function(field){ s += '<li>' + field + '</li>'; }); s += '</ol>'; } //输入字段无效 var invalid = results.getInvalid(); if(invalid.length){ s += '<h4>The following fields are invalid:</h4>' + '<ol>'; baseArray.forEach(invalid, function(field){ s += '<li>' + field + '</li>'; }); s += '</ol>'; } r.innerHTML = s; } } // wait until after our requires are actually loaded. 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, false, true], phone: validate.us.isPhoneNumber }, confirm: { "emailConfirm": "email", "password2": "password" } }; // set up the form handler. var f = query("form")[0]; f.onsubmit = function(e){ baseEvent.stop(e); doCheck(f); }; }); </script> </body> </html>
输出结果:
650) this.width=650;" src="http://img.558idc.com/uploadfile/allimg/210615/1951235533-1.png" title="快照10.jpg" alt="wKiom1RW7M2CQRekAAFU5QLE4is575.jpg" d="3714161" s="46f_f2b" t="jpg">
在基于Dijit的表单里使用dojox/validate
当然,你也可以结合dojox/validate和dijit一起使用,特别是dijit的ValidationTextBox。这里的关键是ValidationTextBox的validator方法。
<!DOCTYPE HTML> <html lang="en"> <head> <meta charset="utf-8"> <title>Demo: DojoX Validation with Dijit Forms</title> <link rel="stylesheet" href="dijit/themes/claro/claro.css"> <script src="dojo/dojo.js" data-dojo-config="async: true, parseOnLoad: true"></script> <style type="text/css"> label { display: inline-block; width: 140px; } </style> <script> require(["dojo/parser", /* dojox/ validate resources */ "dojox/validate/us", "dojox/validate/web", /* basic dijit classes */ "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", "dijit/form/DateTextBox", /* basic dojox classes */ "dojox/form/BusyButton", "dojox/form/CheckedMultiSelect", "dojo/domReady!"]); </script> </head> <body class="claro"> <h1>Demo: DojoX Validation with Dijit Forms</h1> <p style="font-size: x-small"> * 是必填字段. </p> <form data-dojo-type="dijit/form/Form" method="post"> <script type="dojo/method" event="onSubmit"> if(this.validate()){ return confirm('Form is valid, press OK to submit'); }else{ alert('Form contains invalid data. Please correct first'); return false; } return true; </script> <div> <label for="firstName"><strong>First Name*:</strong></label> <input type="text" required="true" name="firstName" id="firstName" placeholder="Your Name" data-dojo-type="dijit/form/ValidationTextBox" missingMessage="Ooops! You forgot your first name!" /> </div> <div> <label for="website"><strong>Website*: </strong></label> <input type="text" required="true" name="website" id="website" placeholder="Your Website" data-dojo-type="dijit/form/ValidationTextBox" validator="dojox.validate.isUrl" /> </div> <div> <label for="email"><strong>Email*:</strong></label> <input type="text" required="true" name="email" id="email" data-dojo-type="dijit/form/ValidationTextBox" validator="dojox.validate.isEmailAddress" /> </div> <div> <label for="bday"><strong>Date of Birth*:</strong></label> <input type="text" required="true" name="bday" id="bday" data-dojo-type="dijit/form/DateTextBox" value="7/5/1983" /> </div> <div> <label for="color"><strong>Favorite Color: </strong></label> <select name="color" id="color" data-dojo-type="dijit/form/FilteringSelect"> <option value="">Select a Color</option> <option value="Red">Red</option> <option value="Green">Green</option> <option value="Blue">Blue</option> </select> </div> <div> <label for="toolkits"><strong>Favorite Toolkits: </strong></label> <select name="toolkits" id="toolkits" data-dojo-type="dojox/form/CheckedMultiSelect" multiple="multiple" style="width:200px;"> <option value="Dojo" selected="selected">Dojo Toolkit</option> <option value="Moo" selected="selected">MooTools</option> <option value="Prototype">Prototype</option> <option value="YUI">YUI</option> <option value="jQuery" disabled>jQuery</option> </select> </div> <div> <label for="MyCheckBox"><strong>Send Emails?:</strong></label> <input id="MyCheckBox" name="MyCheckBox" data-dojo-type="dijit/form/CheckBox" checked="false" /> </div> <div> <label><strong>Email Format: </strong></label> <input type="radio" id="radio1" name="format" checked="checked" data-dojo-type="dijit/form/RadioButton" />HTML <input type="radio" id="radio2" name="format" data-dojo-type="dijit/form/RadioButton" />Text </div> <input type="submit" value="Submit Form" label="Submit Form" id="submitButton" data-dojo-type="dijit/form/Button" /> </form> </body> </html>
输出结果:
650) this.width=650;" src="http://img.558idc.com/uploadfile/allimg/210615/1951235533-1.png" title="快照11.jpg" alt="wKiom1RXMUyg-wdgAAHRRifXUAw620.jpg" d="3714162" s="09f_0b8" t="jpg">