Antd的validator自定义校验导致其它校验规则失效

2,870 阅读1分钟
<FormItem
  label="新账号"
  name="phone"
  rules={[
    { required: true, message: "不能为空" },
    { max: 20, message: "最长20个字符" },
    {
      whitespace: true,
      message: "不能输入空格",
    },
    {
      type: "number",
      transform: (val) => Number(val),
      message: "只能输入数字",
    },
    {
      validator: this.onCheckPhone,
    },
  ]}
>
  <Input placeholder="请输入手机号" />
</FormItem>

我这个自定义检验主要功能是发到后端去查重,同时还需要保留手机号的格式校验,代码如下:

onCheckPhone = (rule, value) => {
  return new Promise(async (resolve, reject) => {
    const { dispatch } = this.props;
    const { currAreaCode } = this.state;
    if (currAreaCode && value) {
      const res = await dispatch({
        type: "userManagement/checkPhone",
        payload: { phone: `${currAreaCode}-${value}` },
      });
      if (typeof res !== "number") {
        resolve();
      } else {
        reject(new Error("该账号已存在!"));
      }
    }
  });
};

代码结构就酱婶,我预想的是,validator 还会和其它校验规则同时校验,但是发现并不能。然后查了查 issue,无果... 果断问了一下度娘,OK,解决。

原来,这个 validator 的规则需要在所有的判断逻辑里面都要加入 callback,保证要覆盖到所有情况,不然就会阻塞其它的校验规则。so...简单改造了一下

onCheckPhone = (rule, value) => {
  return new Promise(async (resolve, reject) => {
    const { dispatch } = this.props;
    const { currAreaCode } = this.state;
    if (currAreaCode && value) {
      const res = await dispatch({
        type: "userManagement/checkPhone",
        payload: { phone: `${currAreaCode}-${value}` },
      });
      if (typeof res !== "number") {
        resolve();
      } else {
        reject(new Error("该账号已存在!"));
      }
    } else {
      // 这里加了一个 resolve
      resolve();
    }
  });
};

由于我用的是 Antd V4,validator 的 API 进行了修改,改用 Promise。所以如果你是老版本用户,直接调用原来的 callback 回调即可。