views:

869

answers:

1

I have a textbox that must have a MIN number of characters as well as a MAX number of characters. What is the best way, using jQuery, to make sure that the input is within the range (while displaying status messages to the user) before allowing the user to submit the form?

Update: the code below works to some degree, however I am getting issues when deleting text. Since it is using 'keypress' to capture events in the textbox, the 'length' variable gets falsely incremented when hitting backspace for example. It seems like the issue is that the length of the text is retrieved before the fact i.e. a keypress will always result in a length of what was there before plus 1. What is the proper way around this?

Update: I think i solved the previous issue by using the keyup function instead of keypress

+1  A: 

If this is the only client side validation in your app (always validate on the server too!) then it'd look something like this:

$("#your_textbox").keypress(function() {
  var length = this.value.length;
  if(length >= MIN && length <= MAX) {
    $("#your_submit").removeAttr("disabled");
    $("#your_validation_div").hide();
  } else {
    $("#your_submit").attr("disabled", "disabled");
    $("#your_validation_div").show();
  }
});

If you need a lot of validation in your application you might want to consider the validation plugin.

Setting the maxlength attribute:

<input type='text' maxlength="30" />
Andy Gaskell
the change() function seems to fire only when I click out of the text box; how can I get this to fire after every new character that is typed into the textbox? thanks
es11
Use keypress instead - I will update the code.
Andy Gaskell
thanks for the update...one last thing - once the length is equal to MAX, how can I disable the textbox so that the user cannot enter any more characters? thanks for your help!
es11
I don't recommend validating minimum lengths on keypress, i recommend validating them on blur instead (but continue to validate maximum lengths on keypress)Suppose the minimum length is 3 characters. The person wants to enter 'abc'. Once they press 'a', there will be an error shown, because only 1 character is in the text field. When they press 'b', the error would still be there. The error message will disappear when they press 'c'. Showing these 'false' error messages while the user is in the process of typing a valid input is confusing.
Chi
@es111: you just need to set the maxlength on your input type text element. I'll edit the code again.
Andy Gaskell