2

I have the following input field:

<input
          type="email"
          id="emailAddr"
          name="emailAddr"
          pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}$"
          placeholder="name@domain.com"
        />

Surprisingly, it allows me to enter the empty email field, whereas if I type something and submit it, it shows an error if the email is not valid.

daniel
  • 369
  • 2
  • 10

2 Answers2

1

As described in the specification, constraint validation for the pattern attribute is not performed if the input value is an empty string.

You need to add a required attribute to your element:

<input
    type="email"
    id="emailAddr"
    name="emailAddr"
    pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}$"
    placeholder="name@domain.com"
    required
/>
Robby Cornelissen
  • 91,784
  • 22
  • 134
  • 156
1

Input already allows for email validation, so no need to add in a pattern, just use:

<input type="email" id="email" name="email">

HTML5 Email Validation

  • Dear @Lucian Alexe: This would not suffice for all scenarios. We need a pattern. It only checks whether @ is used or may be few other stuff. Not all the scenarios. – Imran Rafiq Rather Nov 18 '21 at 08:45
  • There is no absolute perfect regex, that will allow for all scenarios... Try this: /^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/ – Lucian Alexe Nov 18 '21 at 08:54
  • 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](/help/how-to-answer). – Community Nov 18 '21 at 10:43