Except for the pattern
everything is alright and works. You can test it here:
[type="email"] {
padding: .7rem;
border-radius: .3rem;
border: 1px solid gray;
margin-right: 2rem;
}
[type="email"]:invalid {
border: 1px solid red;
}
<label>Your Email
<input type="email" name="email" required placeholder="you@example.com" />
</label>
Not showing errors on empty inputs
It‘s not a good practice to greet the user with a bunch of errors before they entered any data.
Bootstrap uses a .was-validated
class on the <form>
, to hide the error states until that class was added via JavaScript.
.was-validated input:invalid
Another solution without CSS might be the use of the :placeholder-shown
pseudo-class to hide the error state.
This needs a placeholder attribute, which can be set to placeholder=""
.
input:invalid:not(:placeholder-shown) {
border-color: red;
}
/* or, backwards-compatible */
input:invalid {
border-color: red;
}
input:placeholder-shown {
border-color: initial;
}
<label>Your Email
<input type="email" name="email" required placeholder="you@example.com" />
</label>
Beware of restrictive patterns/regex
You should not provide yet another pattern for validation. The browser already has a pattern implemented based on tons of research and with the help of a lot of engineers.
See How can I validate an email address in JavaScript? for some ideas on what you are missing.
I find it important to point this out, as restricting input data is effectively discriminating against users who’s data patterns were missed in the design. This is especially true for groups who are underrepresented in engineering staff.