在Web表单中,我有一个带有RegularExpressionValidator的TextBox对象。我的问题是,当textBox为空时,验证器返回我的字符串(空字符串)有效,但是当我想使用具有相同表达式的代码中的Regex对象再次检查时,结果是空字符串与表达式不匹配。为什么会这样?
这是我的代码:
ASPX:
<table style="background-color:#eeeeee; padding:10">
<tr valign="top">
<td colspan="3">
<asp:Label ID="lblOutput"
Text="Enter a 5-digit ZIP Code"
runat="server"
AssociatedControlID="TextBox1"/>
</td>
</tr>
<tr>
<td colspan="3">
<b>Personal Information</b>
</td>
</tr>
<tr>
<td align="right">
Zip Code:
</td>
<td>
<asp:TextBox id="TextBox1"
runat="server"/>
</td>
<td>
<asp:RegularExpressionValidator id="RegularExpressionValidator1"
ControlToValidate="TextBox1"
ValidationExpression="^\d\d*$"
Display="Static"
ErrorMessage="ZIP code must be 5 numeric digits"
EnableClientScript="False"
runat="server"/>
</td>
</tr>
<tr>
<td></td>
<td>
<asp:Button ID="Button1" text="Validate"
OnClick="ValidateBtn_Click"
runat="server" />
</td>
<td></td>
</tr>
</table>
C#:
protected void ValidateBtn_Click(Object sender, EventArgs e)
{
RegularExpressionValidator minValidator = (RegularExpressionValidator)FindControl("RegularExpressionValidator1");
minValidator.Validate();
if (!minValidator.IsValid)
{
lblOutput.Text = "Page is InValid.";
}
else
{
lblOutput.Text = "Page is Valid.";
}
String exp = @"^\d\d*$";
Regex r = new Regex(exp);
if (r.IsMatch(TextBox1.Text))
{
Response.Write("strings matches");
}
else
{
Response.Write("strings does not matches");
}
}
以下是该页面的截图: