Form的校验方式

18 阅读1分钟
  • async-validator github.com/yiminghe/as…

  • b-validator github.com/PengJiyuan/…

    • 用法类似
    • // 标准用法
      import Schema from 'async-validator';
      
      const descriptor = {
        // name字段的校验规则
        name: {
          type: "string",
          required: true,
          validator(rule, value) {
            return value === "muji"
          },
          message: "输入错误"
        }
      };
      
      const validator = new Schema(descriptor);
      
      validator.validate({ name: "muji" }, (errors, fields) => {
        if (errors) {
          // 校验不通过 do something
          return;
        }
        // 校验通过 do something
      });
      
    • import { Schema } from 'b-validate';
      
      const schema = new Schema({
        name: [
          {
            type: 'string',
            required: true,
            message: '必填字段',
          },
          {
            type: 'string',
            maxLength: 10,
            message: '最大长度是10',
          },
        ],
        age: [
          {
            type: 'number',
            min: 2,
            max: 5,
            message: '在2和5之间',
          },
        ],
        email: [
          {
            type: 'email',
            message: '邮箱格式不对',
          },
        ],
        ip: [
          {
            type: 'ip',
            message: 'ip格式不对',
          },
        ],
        url: [
          {
            type: 'url',
            message: 'url格式不对',
          },
        ],
        custom: [
          {
            validator: (value, callback) => {
              if (value > 10) {
                callback('不能大于10!');
              }
            },
          },
        ],
        // Async validate
        async: [
          {
            validator: async (value, callback) => {
              if (value > 10) {
                callback('不能大于10!');
              }
            },
          },
        ],
      });
      
      schema.validate(
        {
          name: 'pengjiyuan is a nice boy',
          age: 24,
          email: 'pengjiyuan@bytedance.com',
          ip: '127.0.0.1',
          url: 'https://bytedancecom',
          custom: 20,
          async: 20,
        },
        (errors) => {
          console.log(errors);
          /*
           * {
           *  value: 'pengjiyuan is a nice boy', type: 'string', message: '最大长度是10' },
           *  age: { value: 24, type: 'number', message: '在2和5之间' },
           *  url: { value: 'https://bytedancecom', type: 'url', message: 'url格式不对' },
           *  custom: { value: 20, type: 'custom', message: '不能大于10!' }
           * }
           */
        }
      );
      
    • // 在Form.Item使用
      import Schema, {Rules} from 'async-validator';
      // 当前children错误信息
      const [error, setError] = useState('');
      
      const handleValidate = (value) => {
      // 初始化错误信息,用来在最后提交时校验
      let errorMsg = null
      if(Array.isArray(rules)&&rules.length{
      // 将Rules转化成descriptor对象
      const descriptor:Rules = {
          // name是Form.Item 上面的name <Form.Item name={'username'}
          [name]:rules.map(rule=>{
              return {
                  type:'string',
                  ...rule
              }
          })
      }
      
      const validator = new Schema(descriptor);
      
      validator.validate({ [name]:value }, (errors, fields) => {
              if (errors) {
                if (errors?.length) {
                  setError(errors[0].message as string);
                  errorMsg = errors[0].message;
                }
              } else {
                setError('');
                errorMsg = null;
              }
       });
       }
       return errorMsg;
       }