Restricting text box inputs to a given regexp using jQuery

前端 未结 4 2021
被撕碎了的回忆
被撕碎了的回忆 2020-12-20 07:23

Consider the following text box:


Using jQuery I want to restrict the

相关标签:
4条回答
  • 2020-12-20 07:57

    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

    0 讨论(0)
  • 2020-12-20 08:12

    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

    0 讨论(0)
  • 2020-12-20 08:15

    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!

    0 讨论(0)
  • 2020-12-20 08:18

    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]*)$.

    0 讨论(0)
提交回复
热议问题