还有另一个jQuery支持的表单验证器,用于使用自定义验证规则验证表单字段。
1.下载并加载Nice Validator插件。
<script src="/path/to/cdn/jquery.slim.min.js"></script> <script src="/path/to/dist/jquery.validator.min.js?local=en"></script>
2.使用验证表单字段数据-*
属性:
<form class="form" data-validator-option="{timely:2, focusCleanup:true}"> <div class="form-item"> <label class="label">Username</label> <input type="text" name="username" data-rule="required;username;" data-rule-username="[/^[\w\d]{3,12}$/, 'Please enter 3-12 digits, letters, underscores']" data-tip="You can use letters, numbers and periods" > </div> <div class="form-item"> <label class="label">Password</label> <input type="password" name="pwd" data-rule="Password: required; length(8~16)" data-tip="Please fill in at least eight characters" > </div> <div class="form-item"> <label class="label">Verify Password</label> <input type="password" name="pwdAgain" data-rule="Verify Password: required; match(pwd)"> </div> <div class="form-item"> <label class="label">Gender</label> <select name="gender" data-rule="required"> <option value="">select ...</option> <option value="1">Male</option> <option value="2">Female</option> <option value="3">Other</option> </select> </div> <div class="form-item"> <label class="label">Email</label> <input type="text" name="email" data-rule="required;email"> </div> <div class="form-item"> <label class="label">Interest</label> <label><input type="checkbox" name="interest" data-rule="checked">sports</label> <label><input type="checkbox" name="interest">movie</label> <label><input type="checkbox" name="interest">game</label> </div> <div class="form-item"> <label class="label">Note</label> <textarea data-rule="required;"></textarea> </div> <div class="form-item"> <label><input type="checkbox" id="agree_arguments" data-rule="checked">I agree to the service agreement.</label> </div> <div class="form-item"> <button type="submit">Submit</button> </div> </form>
3.或者通过JavaScript。
$('#form').validator({ fields: { 'email': 'required;email', 'pwd': 'required;length(6~16)', // ... } });
4.内置验证规则:
5.创建自定义规则:
// en.js $.validator.config({ // Custom rules rules: { // ... }, });
// or $("#form").validator( rules: { // ... } );
// or via data attribute <input name="demo" data-rule="required;xxx" data-rule-xxx="[/^\d{6}$/, '6 digits']">
// or via JS function mobile: function(element, params) { return /^1[3458]\d{9}$/.test(element.value) || 'Phone Number Validator'; }; // using test function loginName: function(element) { return /^[a-zA-Z]\w{3,}/.test(element.value) || this.test(element, "mobile")===true || this.test(element, "email")===true || 'Input username, phone number, or email'; } // custom ajax validation myRemote: function(element){ return $.ajax({ url: 'check/username.php', type: 'post', data: element.name +'='+ element.value, dataType: 'json' }); }
6.可用的插件选项:
$("#form").validator( // 1 = enable debug // 2 = ignore validation result debug: 0, // 0: validate the form on submit // 1: validate the field when lose focus // 2: validate the field when the value has changed // 3: 1+2 // 8: validate the field when the value has changed and show the result // 9: 1+2 and show the result timely: 1, // theme name theme: 'default', // ignore form fields ignore: '', // ignore empty fields ignoreBlank: false, // move focus to the first invalid field focusInvalid: true, // clear error message when the field got focus focusCleanup: false, // stop the plugin when the first error is captured stopOnError: false, // default CSS classes formClass: 'n-default', validClass: 'n-valid', invalidClass: 'n-invalid', bindClassTo: null, // show success messages showOk: true, // custom error messages msgWrapper: 'span', msgArrow: '', msgIcon: '<span class="n-icon"></span>', msgClass: 'n-right', msgStyle: '', messages: { required: "Please fill in this field", email: "Please enter a valid email address.", // ... }, msgMaker: function(opt) { var html; html = '<span role="alert" class="msg-wrap n-'+ opt.type + '">' + opt.arrow; if (opt.result) { $.each(opt.result, function(i, obj){ html += '<span class="n-'+ obj.type +'">' + opt.icon + '<span class="n-msg">' + obj.msg + '</span></span>'; }); } else { html += opt.icon + '<span class="n-msg">' + opt.msg + '</span>'; } html += '</span>'; return html; }, // custom display display: function(elem) { // ... }, // function(elem) | jqSelector target: null, // apply options & validators to fields fileds: { // ... } // translate ajax response to validation result dataFilter: function (data) { if ( isString(data) || ( isObject(data) && ('error' in data || 'ok' in data) ) ) { return data; } }, // callbacks beforeSubmit: function(form) { // ... }, valid: function(form) { // ... }, invalid: function(form, errors) { // ... }, validation: function(form) { // ... }, msgShow: function($msgbox, type) { // ... }, msgHide: function($msgbox, type) { // ... }, );
7.API方法:
// clear messages $('#form').validator("cleanUp"); // destroy the plugin $('#form').validator("destroy"); // check if is valid $('#field').isValid(function(v){ if (v) { // do something } }); // update options $.validator.config({ // options here }); // set theme $.validator.setTheme("myTheme", { // options here }); // test validation rule $('#form').test(elem, rule); // set form field $('#form').setField(key, field); $('#form')..setField(obj); // show/hide messages $('#form').showMsg(elem, obj); $('#form').hideMsg(elem); // prevent duplicate submit $('#form').holdSubmit(hold);
8.事件:
$('#form').on('validation', function(e, current){ // do something... }); $('#form').on('valid.form', function(e, form){ // do something... }); $('#form').on('invalid.form', function(e, form, errors){ // do something... }); $('#username').on('valid.field', function(e, result){ // do something... }); $('#username').on('invalid.field', function(e, result){ // do something... }); $('#username').on('valid.rule', function(e, ruleName){ if (ruleName === 'remote') { // do something... } }); $('#username').on('invalid.rule', function(e, ruleName){ if (ruleName === 'remote') { // do something... } });