Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent user to type more than 2 digits using JavaScript and JQuery

I have a textbox that holds "From" month. (allows values between 1 and 12 only)

How could I prevent users so that when they try to type 3rd character, javascript would prevent users from typing more than 2 digits?

Here is what I have tried so far but I am not able to get desired result(following script does not work at all)

    $("#monthFromTextBox").bind("change", function (event) {
        var regex = /^\d{1,2}$/g;
        var monthFrom = $(this).find(".monthFrom").text();
        var yearFrom = $(this).find(".yearFrom").text();
        var monthTo = $(this).find(".monthTo").text();
        var yearTo = $(this).find(".yearTo").text();

        // Allow only 1 or 2 digits only
        if (regex.test(monthFrom) === false) {
            event.preventDefault();
            // alert("Month From value should have 1 or 2 digits only");
            return false;
        }
    });
like image 824
dance2die Avatar asked Nov 27 '22 17:11

dance2die


2 Answers

<input type="text" maxlength="2">
like image 180
Esailija Avatar answered Dec 05 '22 01:12

Esailija


for the luls... if you really wanted a JS answer..

$("#monthFromTextBox").on('keydown', function() {
    if (this.value.length > 1) {
        return false;
    }
});​
like image 26
rlemon Avatar answered Dec 05 '22 01:12

rlemon