jquery - Use JavaScript to allow only specific characters in HTML input - Stack Overflow

I have written some JavaScript and jQuery code that accepts only numeric input in a textbox.But this i

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.

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

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.

any tips or ideas?

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.

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

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.

any tips or ideas?

Share Improve this question edited Jan 26, 2012 at 7:52 calvinf 3,9343 gold badges32 silver badges42 bronze badges asked Jan 24, 2012 at 7:33 Jonas LindahlJonas Lindahl 80212 silver badges25 bronze badges 7
  • 1 Have you considered RegEx for this problem? I believe you'll get a much cleaner piece of code from it... :) – FarligOpptreden Commented Jan 24, 2012 at 7:39
  • 2 I'd suggest you don't try to make your keydown handler so fancy - you can't restrict the characters at the beginning of the string unless you can tell where the cursor is. Just restrict it to the characters that can appear anywhere in the string and then use a change and/or blur handler to validate the overall format using a regex - this will also allow for when the user pastes, cuts or drag'n'drops (all of which can be done without triggering keydown). – nnnnnn Commented Jan 24, 2012 at 7:40
  • SSN has 9 digits, even with hyphens the string should not be more then 11 characters. Why is maxNrOfChars set to 12? – Abbas Commented Jan 24, 2012 at 7:53
  • Oh, now I know :). Can you provide a few examples of the valid SSNs? Also, wouldn't it be better to check the SSN on the input box's change event rather then every time a key is pressed? – Abbas Commented Jan 24, 2012 at 8:00
  • well, you could use the 'change'. But that only occurs after it has been filled. so then it has to be writen for informing the user that 19 or 20 has to be included in the start. An example of an SSN would be 197611238899. – Jonas Lindahl Commented Jan 24, 2012 at 8:26
 |  Show 2 more ments

3 Answers 3

Reset to default 3

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/BRewB/2/

Note that .on() is new in jQuery 1.7 and in this case is the same as using .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. 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 plete 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 plete 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/en/JavaScript/Reference/Global_Objects/RegExp

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745251766a4618719.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信