We are using the following to do an email validation in ASP.NET:
\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*
How can this be modified to ignore leading and trailing spaces?
The actual trimming we handle in code on postback but the validator is triggering as being invalid if the user has an extra space often due to copying and paste.
You can place \s*
before and after your pattern and it should work properly.
Group what you want into a named capture and then allow spaces before and after the capture
\s*(?<email>\w+([-+.']\w+)@\w+([-.]\w+).\w+([-.]\w+)*)\s*
Just do the trim before you pass it to the validator.
In case of ASP.NET the following works:
<asp:TextBox runat="server" ID="EmailAddress" />
<asp:RegularExpressionValidator ValidationExpression="\s*\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*\s*" runat="server" ControlToValidate="EmailAddress" Text="*" ErrorMessage="Email is not valid" />
Allows a variety of emails like:
"some@one.com"
" some@one.com "
"so_me@one.co.uk"
" a.s-d__+f@asd.as.as "
etc
Make sure you strip the white spaces in your code like so:
VB Dim Email as string = EmailAddress.Text.Trim()
C# string Email = EmailAddress.Text.Trim();
I was going to "answer" this as a simple comment, but the real answer to your question is that there is no answer.
Why?
Because any email address with space or whitespaces before or after it, is an invalid email address.
You try and pass an email address with whitespace chars around it into an SMPTP control for example, and try and send it, it will fail!
All email addresses have to be validated from the point of view of this regex...
\w+([-+.']\w+)@\w+([-.]\w+).\w+([-.]\w+)*
or even this
/.+@.+/
Anything else is an invalid email address.
Really the way around it is to TRIM() the string before passing into an email control to use it.
Just warning you.