ant design 中的异步表单字段验证

Posted

技术标签:

【中文标题】ant design 中的异步表单字段验证【英文标题】:Async form field validation in ant design 【发布时间】:2019-04-26 08:53:37 【问题描述】:

ant design 中如何异步验证表单域?

 <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 请求完成之前完全执行。那么如何显示错误信息呢?

【问题讨论】:

request 前面不是少了一个await 吗?喜欢 return await request(/api/getZipcodeInfo?zipcode=$zipcode); 顺便说一句:关于异步等待的好文章:jakearchibald.com/2017/await-vs-return-vs-return-await 感谢您提出这个问题! 【参考方案1】:

你是 missing awaitvalidateZipcode 之前和 asynchandlezipCodeChange 之前:

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。

其他解决方案是从validateZipcode 中取消标记async,然后将其用作基于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`);

【讨论】:

【参考方案2】:

关于如何在按钮上应用表单验证的示例,与提交时的表单无关。

按钮示例:

<Button
    id="schematronBtn"
    className="m-2 float-left btn-primary"
    shape="round"
    type="primary"
    onClick=() => this.showSchematronModal()
  >
    t('rulesForm.schematronBtn')
</Button>

字段验证示例:

showSchematronModal() 
  this.formRef.current.validateFields().then(() =>  // validation succeeded
    const  selectStatus  = this.state;
    if (selectStatus === 'DRAFT' || selectStatus === 'PILOT') 
      this.generatedRuleSchematron(true);
     else 
      this.setState( isSchematronModalVisible: true );
    
  ).catch(async e =>  // validation failed, call some validation function
    if (e.errorFields)  // form has errorFields
      await this.onFinishFailed(e);
    
  );

【讨论】:

以上是关于ant design 中的异步表单字段验证的主要内容,如果未能解决你的问题,请参考以下文章

用ant-design在react js中提交后清除表单输入字段值

Vue+Ant Design表单验证

ant-design-vue 表单验证详解

ant-design表单自定义验证

[ React+ant Design] ProFrom高级表单 - 基本的几种格式验证

React开发(130):ant design学习指南之form中的新城多个表单