10

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
  • 1
    Refer to the validator property from the Rule API. Commented Nov 15, 2021 at 5:01

3 Answers 3

20

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>
Sign up to request clarification or add additional context in comments.

4 Comments

What if i get this from backend ? validation_rule = "[{\"rule\" : \"/^[a-zA-Z]{10}$/\", \"msg\" : \"Entered text length must be 10\"}]";
I have to validate the input and show the msg
you could test the regex with /^[a-zA-Z]{10}$/.test(value) and reject with validation_rule.msg, i'll edit the answer
Although if you only want to test if the input passes a regex you can use the native `{ pattern, message } interface like you posted in the question
1

Inside the rules array, you can define a custom validation by this way

<Form>
    <Form.Item
      label="Name"
      name="name"
      rules={[
        {
          required: true,
          message: "The name is required.",
        },
        ({ getFieldValue }) => ({
          validator(_, value) {
            if (regex.test(value)) {
              return Promise.resolve();
            } else {
              return Promise.reject(new Error("Some message here"));
            }
          },
        }),
      ]}
    >
      <Input />
    </Form.Item>
  </Form>

this by using getFieldValue you can access other field values too. it is really helpfull when your validation is dependant on other filed like password and confirm password.

Comments

0

The custom validator function checks if the input matches the regular expression /^[a-zA-Z0-9]+$/. If the value contains non-alphanumeric characters, it returns a rejected promise with an error message. Otherwise, it resolves the promise, indicating successful validation.

For more information on form validation in Ant Design https://ant.design/components/form#formerrorlist

<Form>
    <Form.Item
      label="Name"
      name="name"
      rules={[
        {
          required: true,
          message: "The name is required.",
        },
        {
        validator: (_, value) => {
         if (!/^[a-zA-Z0-9]+$/.test(value)) {
            return Promise.reject(new Error('Name can only include letters and numbers.'));
          }
          return Promise.resolve();
        },
      },
     ]}
    >
      <Input />
    </Form.Item>
   </Form>  

1 Comment

Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.