How to add custom Validation in antd form in react?

Viewed 4752

I am not able to figure out how to add custom validation in antd form in react. Validator function will work or not. Please suggest a suitable approach.

<Form.Item
  label="Name"
  name="name"
  rules={[
    {
      required: true,
      message: 'The name is required.',
    },
    {
      pattern: /^[a-zA-Z0-9]+$/,
      message: 'Name can only include letters and numbers.',
    },
  ]}
>
  <Input />
</Form.Item>
1 Answers

Inside the rules array, you can define a custom validation by defining an async validator function.

<Form>
  <Form.Item
    label="Name"
    name="name"
    rules={[
      {
        required: true,
        message: 'The name is required.',
      },
      {
        message: 'this is custom',
        validator: (_, value) => {
          if (/^[a-zA-Z0-9]+$/.test(value)) {
            return Promise.resolve();
          } else {
            return Promise.reject('Some message here');
          }
         }
       }
     ]}
  >
    <Input />
  </Form.Item>
</Form>
Related