react + antd form表单验证自定义验证validator根据后台接口判断验证

有时候表单中的某些字段是需要调用后台接口验证,比如账号,ID之类的.这时候页面需要根据后台返回结果提示

  // 验证账号是否已经被添加过
  const checkAccount = (value: string | number) => { // 这个是rules自定义的验证方法
    return new Promise((resolve, reject) => {  // 返回一个promise
      checkedAccount({ account: value }).then(res => { // 这个是后台接口方法
        if (res.responseCode === '000000') {
          console.log(11, res.data)
          resolve(res.data)
        } else resolve(false)
      }).catch(error => {
        reject(error)
      })
    })
  }

 <FormItem
     name='account'
     label='账号'
     rules={[
     { required: true, message: '请输入账号!' },
     {
        validator: (rule, value, callback) => {
          checkAccount(value).then(res => {
             if (res) {
                 // console.log(33, res)
                  callback()
              } else {
                  callback('账号已存在')
                      }
               })
         },
      },
      ]}
 >
   <Input placeholder='' />
 </FormItem>
原文地址:https://www.cnblogs.com/steamed-twisted-roll/p/13255866.html