views:

1259

answers:

5

Consider the following text box:

<input type="text" name="quantity" id="quantity_field" />

Using jQuery I want to restrict the set of valid inputs into quantity_field by the following regexp:

<script>
  var quantityRegexp = "^(0|[1-9]+[0-9]*)$";
</script>

More specifically I want to make the browser discard any characters entered into quantity_field that would make the value of the text field not conform to the given regexp. (A corresponding check would of course also be made on the server-side.)

Examples:

  • If the user types "foo 234" only "234" would get entered in the text box.
  • If the user types "001230" only "1230" would get entered in the text box.
  • If the user types "foo1bar" only "1" would get entered in the text box.

Question: What is the simplest way to acheive this using jQuery?

+2  A: 

Not an answer to your question (since I have no knowledge of jQuery), but the regex ^[1-9]*[0-9]*$ might not do as you expect or think. It matches empty strings but also a number like 000000. I expect that you don't want that since your first character class [1-9] explicitly ignores the zero. I think you should change the first * into a +: ^[1-9]+[0-9]*$. However, that regex will reject the (single) number 0. If you want to include that, you should do: ^(0|[1-9]+[0-9]*)$.

Bart Kiers
Good catch! I've adjusted the regexp in the question. Thanks!
knorv
No problem knorv!
Bart Kiers
A: 

I advise you to let the user tpye whatever he wants, then do a validation on submit of the form. (Of course you must still check on the server-side as he could easily disable or alter the javascript validation code)

For validation look into the

jQuery Validation Pluging

jitter
Thanks, but in this case I really want to do the filtering at input time, not at submit time.
knorv
A: 

Define a global variable "oldVal" (not described below), which contains the last known good value. Bind to the keydown action for the input field:

<script>
    $("#quantity_field").keydown(function() {
        var newVal = $("#quantity_field").val();
        var quantityRegexp = /^(0|[1-9]+[0-9]*)$/;

        // success
        if (quantityRegexp.test(newVal)) {
            oldVal = newVal;
            // hide error
            $("#quantity_field_error").hide();
        }

        // else failure
        else {
            $("#quantity_field").val(oldVal);
            // display error message
            $("#quantity_field_error").show();
        }
    });
</script>

This should get you started

wiifm
+1  A: 

If you don't know how many characters the user is going to type in (and just want to restrict them to numbers), the jQuery Validation Plugin is your best bet.

$('form.to-validate').validate({
   rules: {
      quantity: { digits: true }
   }
});

That will only allow the user to enter in digits. If you know how many characters the person is going to type, then I also recommend using the Masked Input plugin for jQuery, which will give the user a nice visual indication of what they need to type and also prevent them from entering in characters you do not want in the field.

If you're not after just digits and must check against a regular expression, this post has the method to add a custom validation method to the jQuery Validation Plugin which should get you what you want.

Hope that helps!

neezer
Thanks, but in this case I really want to do the filtering at input time, not at submit time.
knorv
The Masked input plugin does validation at input time by default, and the jQuery validation plugin can do it on a key-up event (input) if you configure it right. See the `validate()` options in the documentation, specifically `onkeyup: true`.
neezer
Oh, didn't know that. Thanks.
knorv
A: 

jQuery Constrain plugin allows "flexible constraints to be imposed on text boxes" and accepts regular expressions. See this demo.

knorv