jQuery only allow numbers,letters and hyphens

前端 未结 3 1682
执笔经年
执笔经年 2021-01-16 08:25

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 no

3条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-16 08:38

    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, ''));
        }
    });
    

提交回复
热议问题