How to check something isn't an email address?
In web-development circles, it is a well-known fact that trying to validate an email using a regular expression is… complex.
The full set of modern email standards allows for such wonderful addresses as: chief.o'brien+ds9@spásárthach.भारत
So determining whether or not your user has entered a valid email address becomes an ever-increasing challenge.
But what if you have the opposite issue? Suppose you have a form which takes something which mustn't be an email address?
For example - imagine you have a login form which requires a username. And yet your stupid users keep entering their email addresses instead! How can you quickly, cheaply, and simply detect email addresses?
Well, no matter whatever else is in an email address, there will always be an @
somewhere. The @
is necessary but not sufficient for an email address.
So you can use HTML5's pattern
attribute.
Here it is in action:
HTML<input type="text"
pattern="^[^@]+$">
That says "don't accept anything with the @
symbol in it".
We can take it a bit further and add some more attributes to help our users
HTML<input type="text"
pattern="^[^@]+$"
required
placeholder="Your username (which is NOT your email address)"
title="Don't use your email address!!!!!"
id="notemail">
Try it out!
As soon as you type an @
the form will go into an invalid state and can't be submitted. You won't be able to click the login button.
Should You Use This?
Well… perhaps in a pinch. The real solution is to be agnostic towards your users' choice of login. Some may prefer to use an email, some a username. Some may expect their username to start with an @
. Be tolerant of their needs and desires.
Martin A. Brooks :verified_r: said on mastod.no:
@Edent Opinion: the only way to validate an email address is to send an email to it. And even that's not guaranteed because of leaky non-standards based SMTP gateways to walled gardens such as gmail and o365.
Farai said on mastodon.social:
@Edent is it bad that I think the apostrophe is the most confusing part of that email?
Terence Eden said on mastodon.social:
@faraixyz it trips up so many people!
More comments on Mastodon.