Wednesday, 1 March 2017

Validate email address with folder using regex in Javascript



I am writing a regular expression to validate an email address in JavaScript.



/^[a-zA-Z]([\w-\.]{4,29})+@([\w-]+\.)+[a-zA-Z]{2,3}$/



This is working fine. But there came an additional requirement like " In a GMAIL address we can specify the folder name along with the email id to which the mail will be delivered. For ex. james+office@gmail.com , the mail will be delivered to the folder "office" under james@gmail.com's inbox.



So how can I validate that also in the above regex. The Plus symbol is not mandatory but if + is added it should be in between the other characters before @ symbol.


Answer



You can simply add the + character inside of your character class and use a negated match before the @. Note that I removed the escape sequence from the dot and moved the hyphen as the last character, or else you need to escape it and also implemented the use of the i modifier for case-insensitive matching.



/^[a-z]([\w.+-]{4,29})[^+]@([\w-]+\.)+[a-z]{2,3}$/i



Live Demo


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...