daniel
daniel

Reputation: 439

input tag pattern accepting blank values

I have the following input field:

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

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.

Upvotes: 2

Views: 723

Answers (2)

Lucian Alexe
Lucian Alexe

Reputation: 13

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

Upvotes: 1

Robby Cornelissen
Robby Cornelissen

Reputation: 97140

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="[email protected]"
    required
/>

Upvotes: 1

Related Questions