Long live email! Will email ever go away, or will it be like COBOL and FORTRAN and be with us for decades to come?
Notice the trailing space…
The Gripe
I have touched upon UX with password fields in the past. Authentication forms generally include email and password (and sometimes followed by 2FA) fields. If you are like me and like using tools that automate tasks or save time, you have surely run into this issue yourself.
Too many email fields (Web and mobile) don’t perform basic sanity checks or cleanup. If you paste your password (or use a text expansion utility) into the email field, the submit fails during authentication because of a trailing space at the end of your email address.
Sometimes you go through a long onboarding form, hit the submit button, only to fail with an ‘invalid email’ error.
The Solution
The solution is straightforward and should be performed on the client-side. There is no reason to send unvalidated forms to the server.
While option 1️⃣ doesn’t fix the trailing space, it won’t let the form be submitted until it is correct.
1️⃣ HTML validation
HTML form validation with required and pattern.
NOTE: The regular expression above is basic. It turns out writing a regex for all accepted email addresses is quite difficult.
The regex below is advertised to validate 99.9% of email addresses.
(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])
2️⃣ JavaScript validation
The code below is a direct copy from MDN Constraint Validation API.
HTML
<form>
<label for="mail">I would like you to provide me with an e-mail address:</label>
<input type="email" id="mail" name="mail">
<button>Submit</button>
</form>
JavaScript
const email = document.getElementById("mail");
email.addEventListener("input", function (event) {
if (email.validity.typeMismatch) {
email.setCustomValidity("I am expecting an e-mail address!");
} else {
email.setCustomValidity("");
}
});
JavaScript validation with auto-fix
We can take the example above and trim the email field's value as we type or on button click.
A JavaScript String object has a trim method that removes leading and trailing spaces.
var orig = ' foo ';
console.log(orig.trim()); // 'foo'
References
MDN Web Docs - Client-side form validation
MDN Web Docs - String.prototype.trim()