async-validator:规则校验

506 阅读1分钟

文章的源头:上传图片操作出现【规则校验】总是报错的现象,它从而也证明了我对html中form表单知识掌握的不够扎实
一、async-validator源码
1、async-validator使用方法
1)安装依赖:npm i async-validator
2)引入依赖:import Schema from 'async-validator'
3)实际使用:定义一个 descriptor,将其分配给一个 schema,并将要验证的 object 以及一个回调函数传递给该 schema 的validate方法
实例一:

  import Schema from 'async-validator'; // 引入依赖
  // 定义好的descriptor
  const descriptor = { 
    name: {
      type: 'string',
      required: true,
      validator: (rule, value) => value === 'muji',
    },
    age: {
      type: 'number',
      asyncValidator: (rule, value) => {
        return new Promise((resolve, reject) => {
          if (value < 18) {
            reject('too young');  // reject with error message
          } else {
            resolve();
          }
        });
      },
    },
  };
  // 分配schema
  const validator = Schema(descriptor)
  // schema对应的validate方法
  validator.validate({ name: 'muji' },( error, data) => {
    if(error) {
      return handleErrors(errors, fields);}
  })
  validator.validate({ name: 'muji', age: 16 })
  .then(()=>{})
  .catch((errors,fields)=>{
    return handleErrors(errors, fields);
  })

  实例二:

  const descriptor = { 
    name(rule, value, callback, source, options) {
      const errors = [];
      if (!/^[a-z0-9]+$/.test(value)) {
        errors.push(new Error(
          util.format('%s must be lowercase alphanumeric characters', rule.field),
        ));
      }
      return errors;
    }
  }
  const validator = new Schema(descriptor);
  validator.validate({ name: 'Firstname' }, (errors, fields) => {
    if (errors) {
      return handleErrors(errors, fields);
    }
    // validation passed
  });

  实例三:

  const descriptor = {
    email: [
    { type: 'string', required: true, pattern: Schema.pattern.email },
    { 
      validator(rule, value, callback, source, options) {
        const errors = [];
        // test if email address already exists in a database
        // and add a validation error to the errors array if it does
        return errors;
      },
    },
  ],
  }

强烈推荐的几篇文章
1)linjingyi.cn/posts/75b6d…
2)linjingyi.cn/posts/5277a…
3)linjingyi.cn/posts/ea0ec…
4)linjingyi.cn/posts/1f6ad…