validator

功能描述

validator是轻量级表单验证, 基于原生js,仅4kb

依赖插件

快速使用

var validator = new Validator('example_form', [
    {
        name: "req",
        display: "必填字段不能为空",
        rules: 'required'
    }, {
        name: "alphanumeric",
        display: "字数小于5个字符|大于15个字符",
        rules: 'min_length(5)|max_length(15)'
    }, {
        name: "email",
        display: "请输入您的{{email}}|这不是一个邮箱",
        rules: 'required|is_email'
    }, {
        name: "minlength",
        display: "不能为空|至少输入8个字符,您输入的{{minlength}}长度少于8",
        rules: 'required|min_length(8)'
    }, {
        name: "tos_checkbox",
        display: "复选框不能为空",
        rules: 'required'
    }, {
        name: "password",
        display: "1必填",
        rules: 'required'
    }, {
        name: "repassword",
        display: "密码不一致",
        rules: 'same(password)'
    }
], function (obj, evt) {
    if(obj.errors){
        // 判断是否错误
    }
})
validator.validate()

使用说明

new Validator(formName, option, callback)

formName

  • 说明:<form> 中的 id 或者 name 的值

option

  • 说明:验证规则
  • 类型:Array
    • 数组Item
      • 类型:Object
      {
          //name 字段
          name: 'email',
          display:"你输入的不{{email}}是合法邮箱|不能为空|太长|太短",
          // 验证条件
          rules: 'is_email|max_length(12)'
          // rules: 'valid_email|required|max_length(12)|min_length(2)'
      }
      

callback

  • 说明:验证结果回调
  • 参数
    • obj
    obj = {
      callback:(error, evt, handles)
      errors:Array
      fields:Object
      form:form#example_form
      handles:Object
      isCallback:true
      isEmail:(field)
      isFax:(field)
      isIp:(field)
      isPhone:(field)
      isTel:(field)
      isUrl:(field)
      maxLength:(field, length)
      minLength:(field, length)
      required:(field)
    } 
    

方法

validate

validator.validate()

isEmail

validator.isEmail('wowohoo@qq.com') // 返回Boolean

特别说明

更多配置和用法,请参考validator.js

是否仍需要帮助? 请保持联络!
最后更新于 2024/11/18