antd form form validation validateFields mining pit record

When using a form, if you need to validate the input content only on the front end, you can use rules.

 <a-form-item label="姓名" v-bind="formItemLayout">
        <a-input
          class="required"
          placeholder="请输入"
          v-decorator="[
            'name',
            {
              rules: [
                { required: true, message: '姓名不能为空' },
                { min: 2, message: '姓名不能少于2个字' },
                { max: 12, message: '姓名不能大于12个字' },
              ],
            },
          ]"
        />
      </a-form-item>

If you need regular verification, you can also add it to the rules:

 rules: [
                { required: true, message: '姓名不能为空' },
                { pattern: /^\w+$/, message: '仅支持字母数字下划线组合' },
                { min: 2, message: '姓名不能少于2个字' },
                { max: 12, message: '姓名不能大于12个字' },
              ],

The verification timing defaults to change, but can also be changed to blur, etc.

Here comes the pitfall, if you want to use validator, for example:

 <a-input
          v-decorator="[
            'username',
            {
              rules: [
                {
                  validator: this.checkUsername,
                },
              ],
              validateTrigger: ['change', 'blur'],
            },
          ]"
        />

Then you should pay attention when writing this method.

 checkUsername(rule, value, callback) {
      if (!value) {
        callback("登录名不能为空");
      } else if (!/^\w{4,16}$/.test(value)) {
        callback("登录名长度4至16位,包含字母数字或下划线");
      } else {
        this.$get(`user/check/${value}`).then((r) => {
          if (!r.data) {
            callback("抱歉,该用户名已存在");
          } else {
            callback();
          }
        });
      }
    },

That is, callback must be used, that is, even if there is no error and no prompt is needed, a callback() must be written;

Otherwise, when you submit, this.form.validateFields() in the summit method will throw an exception when it is called, but the browser cannot catch it and the console cannot print out the error. The consequence is that you keep clicking the submit button page. Nothing happens, no error is reported on the console, it’s so frustrating. . .

Guess you like

Origin blog.csdn.net/zhuangjiajia09/article/details/124966815