简体   繁体   English

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

[英]Async form field validation in ant design

How to validate form fields asynchronously in 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>

function call函数调用

  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}`);
}

How to show the error message from api response?如何显示来自 api 响应的错误消息? As api call takes some time to complete at that time the validation function call get executed completely before api request complete.由于 api 调用需要一些时间才能完成,此时验证函数调用在 api 请求完成之前完全执行。 So how can i show the error message?那么如何显示错误信息呢?

You're missing await before validateZipcode and async before handlezipCodeChange :你在validateZipcode之前缺少awaithandlezipCodeChange之前的async

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

also, as mentioned in comment, you need to add await to your validateZipcode function:此外,如评论中所述,您需要将await添加到您的validateZipcode函数中:

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

You need to add it because actually, it's impossible to catch completeness of async operation in sync function .您需要添加它,因为实际上, 在同步函数中无法捕获异步操作的完整性

Other solution is to unmark async from validateZipcode , and next use it as Promise-based:其他解决方案是从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}`);
}

Example on how to apply form validation on button, which is not related to form on submit .关于如何在按钮上应用表单验证的示例,这与提交时的表单无关。 Button example:按钮示例:

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

Fields validation example:字段验证示例:

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);
  }
});

} }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM