I am using Aurelia-Validation
in my project and trying to validate email address. When I add an email example@g
, it passes the validation. Shouldn't email validation have .com
, .net
, etc extension at the end to pass the validation? See the plunker link as an example.
Here is the screenshot to show what I mean:
This is a bit nit-picky, but like emix already pointed out in comments, the validation regex used by aurelia-validation
is currently the widely accepted standard as specified by WHATWG. This is the same regex as documented on MDN and w3.org.
Mozilla seems to follow this specification for validating input type="email"
at least. I couldn't find any official sources on chrome or edge though.
The JavaScript version of that regex is:
/^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/
In simple terms this translates to:
@
symbol, any number of alphanumeric characters and (certain) symbols@
symbol, between 1 and 63 alphanumeric characters or hyphens (and cannot start or end with a hyphen)If you want to restrict this validation to emails which are routable in the internet, simply change the asterisk *
at the end of the regex to a plus +
. That keeps the regex identical except there must now be at least one segment starting with a period.
/^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+$/
Made change to my validation rule with below code:
Original code:
ValidationRules.ensure('setEmail')
.displayName('Email')
.required()
.email()
.on(this);
Modified code with matches pattern:
ValidationRules.ensure('setEmail')
.displayName('Email')
.required()
.email()
.matches(/^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/)
.on(this);
See the screenshot:
Invalid:
Valid:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With