Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preventing special character input to html text field

I have an input text field that needs to be limited as to what characters can be typed in. As one form of defense against faulty input, I'm trying to not even let the user type in incorrect things. The input can be [a-zA-Z-._] characters and is limited to 32 characters.

<input id="aliasEntry" type="text" maxlength="32">

As you can see, I've already got the 32 character limit figured out, and the user is prevented from typing any more after the limit has been reached. But I'm having a problem with preventing the input of incorrect characters.

I've tried using jquery's .keypress() and .keydown() event catchers to do things similar to the following:

$("#aliasEntry").keypress(function(e)
{
    var code = e.which || e.keyCode;
    // 65 - 90 for A-Z and 97 - 122 for a-z 95 for _ 45 for - 46 for .
    if (!((code >= 65 && code <= 90) || (code >= 97 && code <= 122) || code == 95 || code == 46 || code == 45))
    {
        var text = $("#aliasEntry").val();
        text = text.substring(0,text.length);
        $("#aliasEntry").val(text);
    }
});

But The problem with this is that the browsers always insert the typed character into the text box AFTER the event has been handled, which makes the code useless because the character I'm trying to eliminate hasn't been entered yet. Is there a way to simply prevent the browser from inserting the character into the text box after the user types it?

like image 968
JDC Avatar asked Aug 23 '10 22:08

JDC


People also ask

How do I turn off special characters in HTML?

Answer: Using htmlspecialchars() function We can remove the HTML special characters from the string using the PHP htmlspecialchars() function. This function converts the HTML special characters within the string into HTML entities.

How do you restrict special characters in a TextBox using regular expression?

var nospecial=/^[^* | \ " : < > [ ] { } ` \ ( ) '' ; @ & $]+$/; if(address. match(nospecial)){ alert('Special characters like * | \ " : < > [ ] { } ` \ ( ) \'\' ; @ & $ are not allowed'); return false; but it is not working.


1 Answers

You're using jQuery, so see this:http://api.jquery.com/event.preventDefault/. Just call e.preventDefault() if the character happens to be invalid, and this should prevent the default browser action from occurring, which in this case would be the insertion of a character.

like image 160
li.davidm Avatar answered Nov 03 '22 01:11

li.davidm