jQuery only allow numbers,letters and hyphens

13,380

Solution 1

You just have to change the regexp to this : "^[a-zA-Z0-9\-]+$".

Note that the hyphen is escaped using \, otherwise it is used to specify a range like a-z (characters from a to z).

This code will only check if the last typed character is in the allowed list, you might also want to check if after a paste in your field, the value is still correct :

// The function you currently have
$('#text').keypress(function (e) {
    var allowedChars = new RegExp("^[a-zA-Z0-9\-]+$");
    var str = String.fromCharCode(!e.charCode ? e.which : e.charCode);
    if (allowedChars.test(str)) {
        return true;
    }
    e.preventDefault();
    return false;
}).keyup(function() {
    // the addition, which whill check the value after a keyup (triggered by Ctrl+V)
    // We take the same regex as for allowedChars, but we add ^ after the first bracket : it means "all character BUT these"
    var forbiddenChars = new RegExp("[^a-zA-Z0-9\-]", 'g');
    if (forbiddenChars.test($(this).val())) {
        $(this).val($(this).val().replace(forbiddenChars, ''));
    }
});

Solution 2

Since there is so much attention on including a hyphen within a character class amongst these answers and since I couldn't find this information readily by Googling, I thought I'd add that the hyphen doesn't need to be escaped if it's the first character in the class specification. As a result, the following character class will work as well to specify the hyphen in addition to the other characters:

[-a-zA-Z0-9]
Share:
13,380
Frank
Author by

Frank

Updated on June 15, 2022

Comments

  • Frank
    Frank almost 2 years

    How can I remove everything but numbers,letters and hyphens from a string with jQuery?

    I found this code which allows only alphanumerical characters only but I'm not sure how I would go about adding a hyphen.

    $('#text').keypress(function (e) {
        var regex = new RegExp("^[a-zA-Z0-9]+$");
        var str = String.fromCharCode(!e.charCode ? e.which : e.charCode);
        if (regex.test(str)) {
            return true;
        }
    
        e.preventDefault();
        return false;
    });
    
  • Sylvain
    Sylvain over 10 years
    You have to escape it, otherwise it will try to detect a range (like a-z : "^[a-zA-Z0-9\-]+$". Also, adding spaces will allow spaces.
  • Sylvain
    Sylvain over 10 years
    @Peter I was indeed waiting for an update of this answer, so I made one myself (with some additions).
  • ridgerunner
    ridgerunner over 10 years
    Note that its also ok to put an unescaped hyphen at the end of a char class.
  • Peter Alfvin
    Peter Alfvin over 10 years
    @Ridgerunner That gives me an error for me. Can you give an example and the version of Ruby you're using?
  • ridgerunner
    ridgerunner over 10 years
    This question is dealing with JavaScript.