ScG
ScG

Reputation: 1073

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 expression validator but no idea what to write?

How can I do it?

Upvotes: 3

Views: 11096

Answers (6)

Lazarus
Lazarus

Reputation: 43064

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?))\://).*).*$"

Upvotes: 1

Rex M
Rex M

Reputation: 144112

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\-\.\?\,\'\/\\\+&amp;%\$#_]*)?");
}

Upvotes: 3

Jan.
Jan.

Reputation: 1995

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 .

Upvotes: 0

StuartLC
StuartLC

Reputation: 107237

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

Upvotes: 0

Joel Coehoorn
Joel Coehoorn

Reputation: 415600

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.

Upvotes: 3

Hidayath
Hidayath

Reputation: 374

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

Upvotes: 0

Related Questions