强大 多语言表单验证插件 jQuery Nice Validator

  • 源码大小:272.69KB
  • 所需积分:1积分
  • 源码编号:19JP-3404
  • 浏览次数:690次
  • 最后更新:2023年06月09日
  • 所属栏目:表单
我要下载
加入收藏
本站默认解压密码:19jp.com 或 19jp_com

简介

还有另一个jQuery支持的表单验证器,用于使用自定义验证规则验证表单字段。

特征:

  • 多种语言(en、ja、zh-cn、zh-tw)。
  • 使用Regex或JS函数的自定义规则。
  • 支持客户端和服务器端验证。
  • 完全可定制,易于扩展。

目录:

  • 验证规则
  • 选项
  • API方法
  • 事件

如何使用它:

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.内置验证规则:

  • 必修的:必填字段
  • 选中的:已检查(n),已检查(n~),已检测(~n),检测(n1~n2)
  • 匹配:match(name),match(neq,name),匹配(lt,name)、匹配(gt,name)和匹配(lte,name)
  • 远程:remote(URL), remote(get:URL), remote(URL, name1, #id2 ...), remote(URL, foo=value1&bar=value2, name3 ...), remote(URL, foo:name1, bar:#id2, name3 ...), remote(jsonpURL), remote(jsonp:URL), remote(cors:post:URL)
  • 整数:integer(+), integer(+0), integer(-), integer(-0)
  • 范围:范围(n~),范围(~n),范围
  • 长度:长度(n),长度(n~),长度
  • 过滤器:筛选器(RegExp)

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...
  }
});

预览截图