使用JavaScript仅允许HTML输入中的特定字符 [英] Use JavaScript to allow only specific characters in HTML input

查看:64
本文介绍了使用JavaScript仅允许HTML输入中的特定字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了一些JavaScript和jQuery代码,只接受文本框中的数字输入。
但这还不够;我需要将输入限制为特定数字。

I have written some JavaScript and jQuery code that accepts only numeric input in a textbox. But this is not enough; I need to limit the input to certain numbers.

此文本框需要处理SSN号码(瑞典SSN),它必须以19或20开头。我想要强迫它从这些数字开始,但我无法将其限制为这些。

This textbox needs to deal with SSN numbers (Swedish SSN), and it has to start with 19 or 20. I want to force it to start with these numbers, but I can't manage to limit it to these.

        $('input.SSNTB').keydown(function (event) {
          var maxNrOfChars = 12;
          var ssnNr = $('input.SSNTB').val();          
        if (event.keyCode == 46 || event.keyCode == 8 || event.keyCode == 9 || event.keyCode == 27 ||
        // Allow: Ctrl+A
        (event.keyCode == 65 && event.ctrlKey === true) ||
        // Allow: home, end, left, right
        (event.keyCode >= 35 && event.keyCode <= 39)) {
            // let it happen, don't do anything               
            return;
        }
        else {              
            // Ensure that it is a number and stop the keypress
            if (((event.keyCode < 48 || event.keyCode > 57) && (event.keyCode < 96 || event.keyCode > 105))) {
                console.log("if-1");
                event.preventDefault();
            }
            if (event.shiftKey == true) {
                console.log("if-3");
                event.preventDefault();
            }
            //rules to make sure the textbox starts with correct number                
            if (event.keyCode != 49 || event.keyCode != 50 || event.keyCode != 97 || event.keyCode != 98) {
                console.log("if-4, Keycode:" + event.keyCode);
                event.preventDefault();
            }
        }
    });

执行最后一个if-case以进行测试。它按计划执行,但不会将输入字符限制为内置的。

The last if-case is executed to for testing this it is. It is executed as planed but it wont limit the input chars as its built for.

任何提示或想法?

推荐答案

您可以使用正则表达式将用户限制为仅输入数字和短划线。使用正则表达式的优势在于用户可以更自然地与输入进行交互,例如,他们可以粘贴到文本输入中,并且将成功验证:

You can use regex to limit the user to only inputting numbers and dashes. Using regex has the advantage that users can more naturally interact with the input, for instance they can paste into the text input and it will be validated successfully:

//bind event handler to the `keyup` event so the value will have been changed
$('.SSNTB').on('keyup', function (event) {

    //get the newly changed value and limit it to numbers and hyphens
    var newValue = this.value.replace(/[^0-9\-]/gi, '');

    //if the new value has changed, meaning invalid characters have been removed, then update the value
    if (this.value != newValue) {
        this.value = newValue;
    }
}).on('blur', function () {

    //run some regex when the user un-focuses the input, this checks for the number ninteen or twenty, then a dash, three numbers, a dash, then four numbers
    if (this.value.search(/[(20)(19)](-)([0-9]{3})(-)([0-9]{4})/gi) == -1) {
        alert('ERROR!');
    } else {
        alert('GOOD GOING!');
    }
});

这是一个演示: http://jsfiddle.net/BRewB/2/

请注意 .on( )是jQuery 1.7中的新功能,在这种情况下与使用 .bind()相同。

Note that .on() is new in jQuery 1.7 and in this case is the same as using .bind().

这篇关于使用JavaScript仅允许HTML输入中的特定字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆