5

I am working with ant design in React.js. I'm trying to validate email with ant design rules. My regex does not work.

<Form.Item>
    {getFieldDecorator('email', {
        initialValue:null,
        rules: [
            {
                required: false,
                pattern: new RegExp("/\S+@\S+\.\S+/"),
                message:
                    'Enter a valid email address!',
            },
        ],
    })(
        <Input
            className="form-control"
            type="text"
            placeholder="Email"
        />,
    )}
</Form.Item>
halfer
  • 19,824
  • 17
  • 99
  • 186
Majedur
  • 3,074
  • 1
  • 30
  • 43
  • 1
    Does this answer your question? https://stackoverflow.com/questions/61314849/how-to-validate-an-email-address-in-react-using-functional-components?rq=1 – Eb Heravi Sep 13 '20 at 09:16

2 Answers2

30

In rules, you can directly make use of the type key with the value email instead of the regex pattern.

Code sample https://codesandbox.io/s/stackoverflowantdemail-9jckh?file=/index.js:916-1352

<Form.Item>
  {getFieldDecorator("email", {
    rules: [
      {
        required: true,
        type: "email",
        message: "The input is not valid E-mail!",
      },
    ],
  })(<Input placeholder="Email" />)}
</Form.Item>;
Subrato Pattanaik
  • 5,331
  • 6
  • 21
  • 52
Hemanthvrm
  • 2,319
  • 1
  • 17
  • 26
9
<Form.Item
    name="email"
    label="E-mail"
    rules={[
      {
        type: 'email',
        message: 'The input is not valid E-mail!',
      },
      {
        required: true,
        message: 'Please input your E-mail!',
      },
    ]}
  >
    <Input />
  </Form.Item>
Hoang Long
  • 446
  • 4
  • 5