简体   繁体   中英

how can i restrict any special characters entered in the textbox

How can I restrict any special characters entered in the textbox? I have a textbox where the user can enter in the textbox to validate if the url exists in the db. Before I hit the db I want to make sure there is no special characters entered in the textbox

for an example if some user try to enter something like: )(*&<>&*^&*^&*$%#!@#$http://www.cnn.com!@#$%^&*()

Before they paste or type the url with special characters how can I not allowed in the textbox?

The only expection to this is: & (ampersand) is allowed if it is in between the url something like this:

http://cnn.com/news/latest.html&id=1

Use the textbox's KeyPress event. In the handler, run the regular expression you want to validate against the e.KeyChar , and if it finds an invalid character, set e.Handled to true . This will prevent the character from being entered in the box.

If you want to test the entire text, you can concatenate the new character and current Text property, and run an expression against that.

Alternatively, use the Validating event to test the entire input when validation is needed.

Edit: In response to the link garykindel posted , KeyPress is going to be a better option than TextChanged or a MaskedTextBox since the former fires events before undoing the change, as well as messes with a user's input position, and a MaskedTextBox too constrictive for something like black-listed characters.

The simplest answer is to just make a method to strip characters on the client side.

$('#myTextBox').keyup(function()
{
     var santizedValue = '';
     for(var j = 0; j < this.value.length; j++)
        if(this.value[j].toLower() == 'a' || this.value[j].toLower() == 'b' ... )
           sanitizedValue += this.value[j];

        //Alternatively; convert the character to integer and check the ASCII range for a-z + &

     this.value = sanitizedValue;
});

You make a similar method on your server (just in case the client doesnt have javascript or defeats the script).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM