How to add custom Validation in antd form in react?
Asked Answered
D

3

8

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>
Deangelo answered 15/11, 2021 at 3:50 Comment(1)
Refer to the validator property from the Rule API.Derbent
M
19

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>
Motoneuron answered 15/11, 2021 at 9:0 Comment(4)
What if i get this from backend ? validation_rule = "[{\"rule\" : \"/^[a-zA-Z]{10}$/\", \"msg\" : \"Entered text length must be 10\"}]";Deangelo
I have to validate the input and show the msgDeangelo
you could test the regex with /^[a-zA-Z]{10}$/.test(value) and reject with validation_rule.msg, i'll edit the answerMotoneuron
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 questionMotoneuron
C
0

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.

Cormorant answered 20/3 at 12:22 Comment(0)
S
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>  
Smriti answered 26/7 at 14:53 Comment(1)
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.Saporous

© 2022 - 2024 — McMap. All rights reserved.