Diskdrive
Diskdrive

Reputation: 18825

How do I make a regular expression trim before validating?

I have a RegularExpressionValidator on my page which validates an email using this

    <asp:RegularExpressionValidator ID="valEmailExpression" 
    runat="server" 
ErrorMessage="Your email address does not appear to be of a valid form. (eg: [email protected])"
    ControlToValidate="txtUsername" EnableClientScript="false" 
    ValidationExpression=**"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"**
    Display="None"></asp:RegularExpressionValidator>

This works for things like "[email protected]"

but if the user cut and pastes emails in, sometimes you get things like "[email protected] " or " [email protected] ".

Is it possible to specify in the regular expression that I would like to trim the white spaces before validating the email?

Upvotes: 6

Views: 5399

Answers (3)

Michel Ayres
Michel Ayres

Reputation: 5985

Try this:

http://www.regular-expressions.info/examples.html

Trimming Whitespace

You can easily trim unnecessary whitespace from the start and the end of a string or the lines in a text file by doing a regex search-and-replace. Search for ^[ \t]+ and replace with nothing to delete leading whitespace (spaces and tabs). Search for [ \t]+$ to trim trailing whitespace. Do both by combining the regular expressions into ^[ \t]+|[ \t]+$ . Instead of [ \t] which matches a space or a tab, you can expand the character class into [ \t\r\n] if you also want to strip line breaks. Or you can use the shorthand \s instead.

hope this will help you.

Upvotes: 1

Alex
Alex

Reputation: 1337

I don't believe you can trim the whitespace in the regex, though you can use the trim function on the string first: http://msdn.microsoft.com/en-us/library/t97s7bs3(v=vs.80).aspx

Upvotes: 0

Andrew Cooper
Andrew Cooper

Reputation: 32576

You could just add white-space checks to your regex:

\s*\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*\s*

Upvotes: 5

Related Questions