input tag pattern accepting blank values

Viewed 100

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.

2 Answers

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
/>

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

Related