Form custom validation rules

During the development process, form form verification is widely used. It can be said that as long as user input is required, there will be verification, otherwise it will be messed up hahaha, but the default verification has wide applicability, but in some special verification requirements And very limited, so you need to have custom validation rules.

Therefore, when using antD's form to manage our form, we need to customize a rule to verify a certain field. At this time, we can add the validator attribute in the rules to point to the method we defined. (For a simple example, my custom verification rule is whether to enter duplicate names)

 <Form.Item
      label="名称"
      labelCol={
   
   { span: 7 }}
      wrapperCol={
   
   { span: 14 }}
 >
            {getFieldDecorator("key", {
              rules: [
                { required: true, message: "请输入名称" },
                { validator: isRepeat } //校验名称是否重复
              ]
            })(<Input placeholder="请输入" maxLength="64" />)}
</Form.Item>
//这个是校验规则的函数  
//rule应该是当前检测form的名称等信息 具体在下面用图展示具体内容
//value表示当前form表单内容,callback则是校验的返回函数
const isRepeat = (rule, value, callback) => {
    if (arrs.length > 0 && arrs.filter(item => item.newKey == value).length > 0) {
      return callback("自定义配置项名称重复");
    } else {
      return callback();
    }
  };

It is worth noting that there must be a callback () When the callback is empty, it means that the verification is passed under this condition, otherwise the name in the callback is the name displayed after the verification fails

↓This is the information of the parameter rule

 

Guess you like

Origin blog.csdn.net/hhhhhhaaaaaha/article/details/127791105