EdzJohnson
EdzJohnson

Reputation: 1175

How can I disable non-romanised characters and symbols in a text field?

I've a registration page and I've disabled the spacebar on the username field using the following code:

<script type='text/javascript'>
//<![CDATA[ 
    $(window).load(function(){
        $("#username").on("keydown", function (e) {
            return e.which !== 32;
        });
    });
//]]>  

</script>

However I've just spotted other characters that are causing issues for the system too. How can I disable any non-romanised characters or other symbols? Things such as this: á,#~!ČΨΩヲЖ

Upvotes: 3

Views: 1672

Answers (2)

Mircea
Mircea

Reputation: 11623

You can create a charCode range and handpick what you need:

$("#username").on("keydown", function (e) {
    var charcode = e.which;
    if ( (charcode === 8) || // Backspace
        (charcode >= 48 && charcode <= 57) || // 0 - 9
        (charcode >= 65 && charcode <= 90) || // a - z
        (charcode >= 97 && charcode <= 122)) { // A - Z
        console.log(charcode)
    } else {
        e.preventDefault()
        return
    }
});

http://jsfiddle.net/CC6BW/3/

Don't forget to preventDefault for what you do not need

The Latin Chart is here: http://www.idautomation.com/product-support/ascii-chart-char-set.html

Upvotes: 1

ASGM
ASGM

Reputation: 11391

You could solve this problem with either regular expressions.

If you just want to include character sets A-Z, a-z, and 0-9 (with no accents), then you can use the following regex to identify whether a character is in those sets:

/^[a-zA-Z0-9]/.test(e)

Better yet, rather than interfering with the user's key entries (which might be frustrating) you could put a warning next to the input when an invalid character is entered. Let's say you had a <span id="warning"></span> next to <input id="username">:

$("#username").on("keydown", function (e) {
    if ( !( /^[a-zA-Z0-9]/.test(e) ) ) {
        $("#warning").text("Only values from a-z, A-Z, and 0-9 are valid");
    }
});

Upvotes: 1

Related Questions