[英]Validation expression in asp.net
如何禁止使用双引号"
在一个文本框
由于您永远无法控制由哪些用户执行客户端操作,因此您最好只在服务器上对其进行检查,因此您可能会使用类似以下的代码:
if (textBox1.Text.Contains("\""))
{
Response.Write("Dey aint no way I'm letting you type that!");
}
使用RegularExpressionValidator
并设置ValidationExpression='^[^\\"]*$'
,这将允许除"
如果您不希望用户首先在文本框中输入引号,请考虑使用AJAX控件工具包中的FilteredTextBox 。
使用RegularExpressionValidator
进行页面输入验证。 .NET验证控件将在用户双方(客户端和服务器端)上验证用户的输入,如果用户禁用了JavaScript,则这一点很重要。 本文还可以帮助您实现ASP.NET服务器控件的验证。
请不要仅使用JavaScript或AJAX来执行此操作 。 始终执行服务器端输入验证! 尤其是当您将用户的输入写回到数据库中时( SQL注入 )。
您尚未指定使用的是Webforms还是MVC,因此我将抛出一些问题。
首先,这是在两种情况下都将使用的Regex。 ^[^\\"]*$
WebForms的第一个
<asp:TextBox runat="server" id="TextBox1" />
<asp:RegularExpressionValidator runat="server" id="Regex1" controltovalidate="TextBox1" validationexpression="^[^\"]*$" errormessage="Nope!" />
<!-- This will give you client AND server side validation capabilities-->
为了确保您在SERVER SIDE上有效,请将其添加到表单提交方法中
If Page.IsValid Then
''# submit the form
Else
''# your form was not entered properly.
''# Even if the user disables Javascript, we're gonna catch them here
End If
在MVC中,您绝对应该在ViewModel上使用DataAnnotations
注意:如果您打算进行很多重复的ctrl + C和ctrl + V, DataAnnotations也可以用于WebForms。
''# fix SO code coloring
''# this is in the view model
<RegularExpression("^[^\"]*$", ErrorMessage:="Nope")>
Public Property TextBox1 As String ''# don't actually call it TextBox1 of course
在控制器的“发布”操作中,您想要添加以下内容
If ModelState.IsValid Then
''# submit the form
Else
''# your form was not entered properly.
''# Even if the user disables Javascript, we're gonna catch them here
End If
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.