RegEx Validation Control Bug??

  • Thread starter Thread starter Mike
  • Start date Start date
M

Mike

I'm trying to have a form where a user has to enter a valid email address, and
I'm trying to use the RegEx Validation control to do that. The problem is that
when a user submits the form with a blank line, it is ACCEPTED even though it
does not pass the pattern match in the expression.

Another problem is that if there are leading spaces or trailing in a valid email
address, the expression fails.

Case 1:(blank) : PASSES (it shouldn't)
Case 2: (e-mail address removed) : FAILS (leading spaces)
Case 3:[email protected] : FAILS (trailing spaces)


<form id="Form1" method="post" runat="server">
Enter your Email address:
<asp:TextBox id="txtEmail" runat="server"></asp:TextBox>
<asp:RegularExpressionValidator id="valRegExEmail" runat="server"
ErrorMessage="Enter a valid email address"
ValidationExpression="\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"
ControlToValidate="txtEmail">*</asp:RegularExpressionValidator>
<br>
<asp:Button id="Button1" runat="server" Text="Button"></asp:Button>
<br>
<asp:ValidationSummary id="ValidationSummary1"
runat="server"></asp:ValidationSummary>
</form>
 
I think in the documentation it says all validators accept empty string as
valid except the required validator.
 
You need to run a Required Field validation control first, then the regular
expression like this:

<form id="Form1" method="post" runat="server">
Enter your Email address:
<asp:TextBox id="email" runat="server" />
<asp:RequiredFieldValidator
id="RequiredEmail"
runat="server"
ControlToValidate="email"
ErrorMessage="<br>* Email address is required"
Display="Dynamic"
/>
<asp:RegularExpressionValidator
id="RegExpEmail"
runat="server"
ControlToValidate="email"

ValidationExpression="^[a-zA-Z][\w\.-]*[a-zA-Z0-9]@[a-zA-Z][\w\.-]*[a-zA-Z0-
9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]$"
ErrorMessage="<br>* Email is not in a valid format"
Display="Dynamic"
/>
<br>
<asp:Button id="Button1" runat="server" Text="Button"></asp:Button>
<br>
</form>
 
You need to use a required field validator in conjunction with a regular
expression validator. I'm guessing Microsoft have done it this way for
scenarios where fields only need to be validated if data is entered, though
it would have been nice if they could have added an option into the other
validators where you can force a field to be required.

As for the spaces problem... You could modify the regular expression to
allow leading or trailing spaces, and then trim the whitespace from the
string on the server side. Another way to do it, would be to write a
javascript function to trim the spaces client side, and update the textbox.

I.e.

<script language="javascript">
<!--
function trimWhitespace(e)
{
e.value = e.value.trim();
}
</script>

Add this to the textbox, in the codebehind file:

txtEmail.Attributes.Add("onChange", "trimWhitespace(this)")


Hope this helps,

Mun
 
Back
Top