tags:

views:

478

answers:

3

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.

+7  A: 

just do the trim before you pass it to the validator

Kevin
It is an asp.net validator linked to a textbox, so not sure that is possible by default. I'd prefer to have the regex handle it if possible.
schooner
Why? The spaces are *not* part of a valid email, so the regex shouldn't see them. Trim the value with an onchange/onsubmit action.
Peter Boughton
+4  A: 

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*
Jeff Moser
Not to forget "^" and "$".
Tomalak
A: 

You can place \s* before and after your pattern and it should work properly.

localshred
Why in the world did Sebastian and I get a down vote? For answering the question 20 seconds later?
localshred