4

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;
        }
    });
2
  • 2
    No need to use such complicated logic, a simple attribute on the input element will do maxlength like esailija has posted. Commented May 25, 2012 at 14:33
  • 1
    This isn't really going to validate the input if that's what you're going for. They could still enter something like "15" for the month Commented May 25, 2012 at 14:39

3 Answers 3

18
<input type="text" maxlength="2">
Sign up to request clarification or add additional context in comments.

3 Comments

rlemon, why depend on javascript when you can get it done with html ?
@rlemon: it's ok Esailija's answer solved the question ;) but cannot mark it as an answer within 10 minutes
umm, he doesn't need Javascript.
8

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

$("#monthFromTextBox").on('keydown', function() {
    if (this.value.length > 1) {
        return false;
    }
});​

5 Comments

I think you should use if ($(this).val().length > 1)
lol... my bad. it isn't a troll answer :P it's valid... just not needed.
I think this is a valid answer as well for me. I could use rlemon's logic to prevent users to enter invalid months or years.
This is less pointless than you think - maxlength doesn't work if your input has type=number, so an approach like this is helpful for limiting the number of digits the user can type.
Unfortunately, though, it's wrong - this also prevents the user from deleting characters with the delete or backspace keys once they've hit the max length, which is plainly undesirable.
1

I know you asked for a JavaScript solution but I don't think you need one.

Why not simply restrict the text box in HTML:

<input type="text" maxlength="2" size="10" value="" name="monthFromTextBox">

This way, you're covered even if JavaScript's turned off.

Just remember to verify it server-side too if it's an important restriction.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.