蚂蚁设计中的异步表单字段验证

时间:2018-11-23 19:06:24

标签: async-await antd ant-design-pro

如何在ant设计中异步验证表单字段?

 <FormItem>
     {getFieldDecorator('zipcode', {
       initialValue: `${customer && customer.zipcode ? customer.zipcode : ''}`,
       rules: [
         // { required: true, message: 'Please input your Zipcode' },
         { validator: this.handlezipCodeChange },
       ],
     })(
       <Input
         prefix={
           <Icon type="zipcode" style={{ color: 'rgba(0,0,0,.25)', visibility: 'hidden' }} />
         }
         type="number"
         placeholder="Zipcode"
         // onChange={this.handlezipCodeChange}
       />
     )}
</FormItem>

函数调用

  handlezipCodeChange = (rule, value, callback) => {
    if (!value) {
      callback('Please input your zipcode');
    }
    if (value.length < 5) {
      callback('Please enter minimum length of 5');
    }
    if (value.length > 5) {
      callback('Please enter maximum length of 5');
    }
    if (value.length === 5) {
      const validateZipCode = validateZipcode(value);
      if (
        validateZipCode &&
        validateZipCode.result &&
        validateZipCode.result.zipcodeInfo === null
      ) {
        callback('Seems to be Invalid Zipcode');
      } else {
        callback();
      }
    }
  };

export async function validateZipcode(zipcode) {
  return request(`/api/getZipcodeInfo?zipcode=${zipcode}`);
}

如何显示api响应中的错误消息?由于api调用需要花费一些时间才能完成,因此在api请求完成之前,验证功能调用将完全执行。那么如何显示错误消息?

1 个答案:

答案 0 :(得分:2)

您是await之前的missing validateZipcodeasync之前的handlezipCodeChange

handlezipCodeChange = async (rule, value, callback) => {
   ...
  if (value.length === 5) {
      const validateZipCode = await validateZipcode(value);
     ...
}

此外,如注释中所述,您需要向await函数中添加validateZipcode

export async function validateZipcode(zipcode) {
  return await request(`/api/getZipcodeInfo?zipcode=${zipcode}`);
}

您需要添加它,因为实际上是it's impossible to catch completeness of async operation in sync function

其他解决方案是从async中取消标记validateZipcode,然后将其用作基于Promise的

handlezipCodeChange = (...) => {
  ...
  if (value.length === 5) {
    const successHandler = ({result = {}}) => result.zipcodeInfo === null ? callback('Seems to be Invalid Zipcode') : callback();

    validateZipcode(value)
      .then(successHandler)
      .catch( error => callback("Can't validate zip code") );

  }
}

export function validateZipcode(zipcode) {
  return request(`/api/getZipcodeInfo?zipcode=${zipcode}`);
}