简体   繁体   English

使用JavaScript仅允许HTML输入中的特定字符

[英]Use JavaScript to allow only specific characters in HTML input

I have written some JavaScript and jQuery code that accepts only numeric input in a textbox. 我已经编写了一些JavaScript和jQuery代码,它们仅接受文本框中的数字输入。 But this is not enough; 但这还不够; I need to limit the input to certain numbers. 我需要将输入限制为某些数字。

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. 该文本框需要处理SSN编号(瑞典语SSN),并且必须以19或20开头。我想强迫它以这些编号开头,但是我无法将其限制为这些编号。

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

The last if-case is executed to for testing this it is. 最后一个if-case被执行以对其进行测试。 It is executed as planed but it wont limit the input chars as its built for. 它按计划执行,但不会限制输入字符的构建长度。

any tips or ideas? 有什么提示或想法吗?

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

Here is a demo: http://jsfiddle.net/BRewB/2/ 这是一个演示: http : //jsfiddle.net/BRewB/2/

Note that .on() is new in jQuery 1.7 and in this case is the same as using .bind() . 请注意, .on()是jQuery 1.7中的新功能,在这种情况下与.bind()相同。

Thought I would post the solution that came to the end. 以为我会发布解决方案。 I actually kept the similar code that I posted above and did not covert this it RegExp. 实际上,我保留了上面发布的类似代码,但没有对此进行RegExp保密。 What was done was to verify the number after focus on this textbox is lost. 所做的是在失去对这个文本框的关注之后验证数字。 It it is incorret the user will be informed and forced to fill in a valid number. 如果不正确,用户将被告知并被迫填写有效号码。

$('input.SSNTB').focusout(function () {
    var ssnNr = $('input.SSNTB').val();
    var ssnNrSub = ssnNr.substring(0, 2);
    //console.log(ssnNrSub);

    //checks for correct lenggth
    if (ssnNr.length < 12) {
        $('div.SSNHelp label.Help').html('SSN to short. Please fill in a complete one with 12 numbers');
        setTimeout(function () {
            $('input.SSNTB').focus();
        }, 0);
        validToSave = false;
        return;
    }

    //checks so it starts correct
    if (ssnNrSub != "19" && ssnNrSub != "20") {
        $('div.SSNHelp label.Help').html('The SSN must start with 19 or 20. Please complete SSN.');
        setTimeout(function () {
            $('input.SSNTB').focus();
        }, 0);
        validToSave = false;
        return;
    }

    $('div.SSNHelp label.Help').html('');
    validToSave = true;
    });

Works for me. 为我工作。 : ] :]

You have to use regex. 您必须使用正则表达式。 Regex is of help in these kind of situations. 正则表达式在这种情况下会有所帮助。

Learn more about it from https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/RegExp https://developer.mozilla.org/zh-CN/JavaScript/Reference/Global_Objects/RegExp了解更多

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM