Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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? As api call takes some time to complete at that time the validation function call get executed completely before api request complete. So how can i show the error message?

like image 674
Srikanth Gowda Avatar asked Nov 23 '18 19:11

Srikanth Gowda


People also ask

How do you use the getFieldDecorator in ANTD?

Just use Form. Item directly: // antd v3 const Demo = ({ form: { getFieldDecorator } }) => ( <Form> <Form. Item> {getFieldDecorator('username', { rules: [{ required: true }], })(<Input />)} </Form.

What is getFieldDecorator?

getFieldDecorators is a Two-way binding for form . There is no getFieldDecorators in React, this is an ant-design API.

What are form validators?

Form validation is a “technical process where a web-form checks if the information provided by a user is correct.” The form will either alert the user that they messed up and need to fix something to proceed, or the form will be validated and the user will be able to continue with their registration process.

How do you display the first item by default in a dynamic ANTD form?

You have to click the "+ Add Field" button for the dynamic form to add and show the first field as shown here..


1 Answers

You're missing await before validateZipcode and async before handlezipCodeChange:

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:

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:

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}`);
}
like image 51
Alex Avatar answered Oct 09 '22 08:10

Alex