Prevent special characters in a TextBox
I want to prevent users from entering url's (like a href="") in a TextBox.
I want to use a regular expressio开发者_JS百科n validator but no idea what to write?
How can I do it?
Do you mean you literally want to prevent them from entering the text href="
in the TextBox, or you want to prevent URLs? Either way, a RegexValidator is one solution:
Actually, as far as I know there is not a very easy way to use an OOTB-regex validator to do a negative contains (i.e. "fail if any match"). Someone smarter may be able to correct me on that. But you can definitely use a custom validator:
<asp:TextBox runat="server" id="myTextBox" />
<asp:CustomValidator runat="server" OnServerValidate="ValidateNoUrls" ControlToValidate="myTextBox" ErrorMessage="URLs not allowed" />
Codebehind:
protected void ValidateNoUrls(object sender, ServerValidateEventArgs e)
{
e.IsValid = !Regex.IsMatch(e.Value, @"(ht|f)tp(s?)\:\/\/[0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*(:(0-9)*)*(\/?)([a-zA-Z0-9\-\.\?\,\'\/\\\+&%\$#_]*)?");
}
javascript + regex will do this, but there's no standard code method I can point you to.
The important thing to remember, though, is that no matter what you do, you can't prevent users from submitting a request to your server with the bad stuff in it. That means anything you do on the client web browser with javascript is only a band-aid and is there to help your users know where the lines are. It's not the real security code. The real security code must be on your server. That's where you need to know how to handle things like web addresses entered in a textbox.
As you mention ASP.NET you might want to try a Regex Validator which checks the input to ensure there are no URL patterns present. Have a look at this MSDN Article.
This regex should do the trick: @"^(?!.*(mailto\:|(news|(ht|f)tp(s?))\://).*).*$"
You can use the keypress JS event and check to see if the pattern entered matches what you want to filter, You can also use the onblur event to do the samething
You might need to consider doing validation (or stripping) on the server in any event, as a malicious user may do a direct HTTP POST and bypass your javascript
Also make sure that you don't validate only on the client side via JS or alike. If we're speaking of a web-application, then you must do server-side validation. That is, because you'll never know how a request was formed and where it comes from. It's easy to form any GET/POST request without even looking at your .
精彩评论