async-validator 教程

1,252 阅读2分钟

npm地址

www.npmjs.com/package/asy…

安装

npm i async-validator

用法

基础的用法是先定义一个descriptor对象。

import Schema from 'async-validator';

const descriptor = {
  name: {
    // 同步自定义验证函数。里面不能作异步校验。
    // 返回true代表校验成功,返回false代表失败
    // 使用自定义验证函数,其它规则都会失效。
    required: true, // 建议显示指定required的值。是否必须校验。
    validator: (rule, value) => {
      return value === 'xiaoming'
      // 不可以返回Promise,否则永远验证通过
    }
    
  },
  age: {
    required: true, // 必传age属性。默认为true
    type: 'number',
    min: 1,
    max: 10
  },
  gender: {
    // 异步自定义验证函数,返回Promise
    // 如果被验证的对象没有gender属性,则不会走这个验证函数
    required: false,
    asyncValidator: (rule, value) => {
      return new Promise((resole, reject) => {
        setTimeout(() => {
          resole(value)
        }, 500);
      })
      // return true。
    }
  }
};

const validator = new Schema(descriptor);

// Promise形式
validator.validate({ name: 'xiaoming' }, { 
    suppressWarning: false, // 这里没搞懂这个属性是干什么的。 
    first: false, // 默认为true。为false后,有一个验证失败后,后面就不再验证了 
    firstFields: false // 默认为ture。为false后,当一个属性有多个校验规则时,有一个验证失败后,后面就不再验证了 }
).then((fields) => {
  // 验证通过
  console.log('验证成功', fields)
}).catch(({ errors, fields }) => {
  // 验证失败
  console.log('验证失败', fields)
});

执行这段代码会打印什么呢?

会打印验证失败。因为被验证对象只有name属性,而验证规则指定required: true的属性还有age, 也就是说还必须传递age属性。

image.png

然后改一改

// Promise形式
validator.validate({ name: 'xiaoming', age: 5 }).then((fields) => {
  // 验证通过
  console.log('验证成功', fields)
}).catch(({ errors, fields }) => {
  // 验证失败
  console.log('验证失败', fields)
});

此时打印验证成功

image.png

验证方式也可以使用callback回调函数形式

const validator = new Schema(descriptor);

// // Promise形式
// validator.validate({ name: 'xiaoming', age: 5 }, {suppressWarning: false, first: false, firstFields: false}).then((fields) => {
//   // 验证通过
//   console.log('验证成功', fields)
// }).catch(({ errors, fields }) => {
//   // 验证失败
//   console.log('验证失败', fields)
// });

validator.validate({ name: 'xiaoming', age: 5 }, {
    suppressWarning: false,  // 这里没搞懂这个属性是干什么的。
    first: false, // 默认为true。为false后,有一个验证失败后,后面就不再验证了
    firstFields: false // 默认为ture。为false后,当一个属性有多个校验规则时,有一个验证失败后,后面就不再验证了
  }, 
  (errors, fields) => {
      if (errors) {
        // 验证失败
        return console.log('验证失败', fields)
      }
        // 验证通过
        console.log('验证成功', fields)
});

还可以为其指定多个验证规则

  age: [
    {
            required: true,
            type: 'number',
    },
    {
            type: 'number',
            required: true,
            min: 1,
            max: 100
    }
],

其中type的值可以为以下这些:

要注意string为默认值

  • string: Must be of type stringThis is the default type.
  • number: Must be of type number.
  • boolean: Must be of type boolean.
  • method: Must be of type function.
  • regexp: Must be an instance of RegExp or a string that does not generate an exception when creating a new RegExp.
  • integer: Must be of type number and an integer.
  • float: Must be of type number and a floating point number.
  • array: Must be an array as determined by Array.isArray.
  • object: Must be of type object and not Array.isArray.
  • enum: Value must exist in the enum.
  • date: Value must be valid as determined by Date
  • url: Must be of type url.
  • hex: Must be of type hex.
  • email: Must be of type email.
  • any: Can be any type.