使用 RegularExpressionValidator 进行 IP 验证不起作用
我尝试使用必需的提交验证器来实现 IP 地址验证,但它似乎不起作用,它显示错误 “无法识别的转义序列”
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server"
ControlToValidate="txtadapterid" ErrorMessage="Please Enter a Valid IP Address"
Font-Size="Small"
ValidationExpression="^(([01]?\d\d?|2[0-4]\d|25[0-5])\.){3}([01]?\d\d?|25[0-5]|2[0-4]\d)$"></asp:RegularExpressionValidator>
并且代码文件方法是
private void checkRejex(string strFindin)
{
Regex myRegex = new Regex("^(([01]?\d\d?|2[0-4]\d|25[0-5])\.){3}([01]?\d\d?|25[0-5]|2[0-4]\d)$");
if (myRegex.IsMatch(strFindin))
{
lblmsg.Text = "Valid Input";
lblmsg.ForeColor = Color.Green;
}
else
{
lblmsg.Text = "Please enter a valid IP Address";
lblmsg.ForeColor = Color.Red;
}
}
I tried to implement the IP address validation using Required filed validator but it doesn't seem to work its displaying error "Unrecognized Escape Sequence"
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server"
ControlToValidate="txtadapterid" ErrorMessage="Please Enter a Valid IP Address"
Font-Size="Small"
ValidationExpression="^(([01]?\d\d?|2[0-4]\d|25[0-5])\.){3}([01]?\d\d?|25[0-5]|2[0-4]\d)$"></asp:RegularExpressionValidator>
and the code file method is
private void checkRejex(string strFindin)
{
Regex myRegex = new Regex("^(([01]?\d\d?|2[0-4]\d|25[0-5])\.){3}([01]?\d\d?|25[0-5]|2[0-4]\d)$");
if (myRegex.IsMatch(strFindin))
{
lblmsg.Text = "Valid Input";
lblmsg.ForeColor = Color.Green;
}
else
{
lblmsg.Text = "Please enter a valid IP Address";
lblmsg.ForeColor = Color.Red;
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
而不是像您这样带有反斜杠的纯字符串:
您需要使用带有
@
前缀的逐字字符串,如下所示:@
防止反斜杠被解释为字符串的一部分,而是使它们按照您的预期传递到正则表达式。有关完整详细信息,请参阅文档中的字符串文字 。
Rather than a plain string with backslashes, as you have:
you need to use a Verbatim String, prefixed with an
@
, like this:The
@
prevents the backslashes being interpreted as part of the string, but instead causes them to be passed through to the Regex as you intended.See String literals in the documentation for full details.
在 C# 字符串中,反斜杠字符 (
\
) 具有特殊含义:它是转义字符。您需要使用双反斜杠来消除特殊含义:或者通过在其前面添加 @ 来使用逐字字符串文字,其中反斜杠没有特殊含义:
在逐字字符串中,仅使用双引号 (
"
)需要转义(再次使用一对""
),因为它们用于分隔字符串。In C# strings the backslash character (
\
) has a special meaning: it's an escape character. You need to use double backslashes to take away the special meaning:Or use a verbatim string literal by prefixing it with @, where the backslash has no special meaning:
In verbatim strings only the double quotes (
"
) need to be escaped (again, by using a pair""
) because they're used to delimit the string.