簡體   English   中英

螞蟻設計中的異步表單字段驗證

[英]Async form field validation 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>

函數調用

  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 請求完成之前完全執行。 那么如何顯示錯誤信息呢?

你在validateZipcode之前缺少awaithandlezipCodeChange之前的async

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

您需要添加它,因為實際上, 在同步函數中無法捕獲異步操作的完整性

其他解決方案是從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}`);
}

關於如何在按鈕上應用表單驗證的示例,這與提交時的表單無關。 按鈕示例:

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

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM