How to开发者_开发技巧 disallow use of double quotes "
in a textbox
Use String.Contains()
Since you can never control what users do the client you might as well just check it on the server, so you would probably use code something like:
if (textBox1.Text.Contains("\""))
{
Response.Write("Dey aint no way I'm letting you type that!");
}
use RegularExpressionValidator
and set the ValidationExpression='^[^\"]*$'
, that will allow anything, including empty, other than "
If you don't want users to be able to type quotes in the textbox in the first place, consider using a FilteredTextBox from the AJAX Control Toolkit.
Use the RegularExpressionValidator
for your page input validation. The .NET validation controls will verify your users' input on both sides, the client-side, and the server-side which is important if the user has disabled JavaScript. This article might also help you to implement the validation of your ASP.NET server controls.
Please don't do this just with JavaScript or AJAX. Always perform a server-side input validation! Especially if you are writing the users' input back into a database (SQL Injections).
You haven't specified if you're using webforms or MVC, so I'm gonna throw a couple things a'cha.
First off, here's the Regex you'll use in either situation. ^[^\"]*$
First for 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-->
To ensure you're valid on the SERVER SIDE, you add this to your form submit method
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
In MVC you should definitely use DataAnnotations on your ViewModel
NOTE: DataAnnotations can also be use for WebForms if you're planning on doing a lot of repeat ctrl + C and ctrl + V
''# 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
And in your controller "Post" action, you wanna add the following
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
精彩评论