Skip to content Skip to sidebar Skip to footer

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. But this is not enough; I need to limit the input to certain numbers. This textbox need

Solution 1:

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 hyphensvar newValue = this.value.replace(/[^0-9\-]/gi, '');

    //if the new value has changed, meaning invalid characters have been removed, then update the valueif (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 numbersif (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/

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

Solution 2:

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 lenggthif (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 correctif (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. : ]

Solution 3:

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

Post a Comment for "Use Javascript To Allow Only Specific Characters In Html Input"