Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 875
Diskdrive Avatar asked May 27 '11 01:05

Diskdrive


2 Answers

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

\s*\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*\s*
like image 98
Andrew Cooper Avatar answered Nov 21 '22 22:11

Andrew Cooper


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.

like image 31
Michel Ayres Avatar answered Nov 21 '22 21:11

Michel Ayres