How not to check email address validity
I recently had to fill in a form on the USPS website requesting me to reconfirm my email preferences. They were kind enough to prepopulate all of the fields with my account data. However, when I went to submit the form, it complained with “You must enter a valid email address”.
I thought this was odd, because they had already accepted my email address in the past, and besides, the email address I use for the account is perfectly valid and doesn’t exercise any of the oddities permitted by the relevant RFCs. After digging about in the page’s sources, I eventually traced my way the javascript file that did the validation (archived). In it, you find the following regex
var emailRegex = /^[a-z][a-zA-Z0-9_.]*(\.[a-zA-Z][a-zA-Z0-9_.]*)?@[a-z][a-zA-Z-0-9]*\.[a-z]+(\.[a-z]+)?$/i
where validation is done by checking
validEmail = (!emailRegex.test(emailField)) ? false : true;
[...]
if(!validEmail ) {
$('#email-error').html('You must enter a valid email address.');
$('#emailAddress').css('border-color', '#e71921');
}
There are several things wrong with the above check:
- It doesn’t accept emails whose local part starts with 0-9 (this is why my email address was rejected).
- It doesn’t accept emails whose domain starts with 0-9
- Why bother specifying
[a-zA-Z]
if you’re going to make the regex case insensitive with/i
at the end? - How many other things can you find?
I managed to circumvent the broken check by editing the javascript in-browser and reported the issue via their technical support form, but the broken validation is still there.
Comments: To comment on this post, send me an email following the template below. Your email address will not be posted, unless you choose to include it in the link: field. If your web browser is configured to handle mailto: links, click comment to load the template into your mail client.
To: Ryan Kavanagh <rak@rak.ac> Subject: [blog-comment] /blog/2018-03-30-how-not-to-check-email-validity/ post_id: /blog/2018-03-30-how-not-to-check-email-validity/ author: [How should you be identified? Usually your name or "Anonymous"] link: [optional link to your website] Your comments here. Markdown syntax accepted.
1 Comment
Daniel Aleksandersen
As for how to do it correctly: leave it up to the web browser (but confirm server-side using a better language than JavaScript). <input required type="email">