1

I can get it to only allow numbers only but I need help with:

  1. Only the first number can be bigger than 0
  2. The user can enter a maximum of 9 characters and a minimum of 2 characters, then they must enter a decimal point.
  3. After the decimal they must only enter 2 more numbers.

    $("#mytextbox").on("keypress", function(event) {
    
        var ValidPrice = /[1-9][0-9]/;
        var key = String.fromCharCode(event.which);
    
        if (event.keyCode == 8 || event.keyCode == 37 || event.keyCode == 39 || ValidPrice.test(key)) {
            return true;
        }
    
        return false;
    });
    
    $('#mytextbox').on("paste",function(e) {
        e.preventDefault();
    });
    
Mike Cluck
  • 31,869
  • 13
  • 80
  • 91

1 Answers1

1

To force a number larger than 0, your first part, [1-9] should work.

For two to nine characters (or one through eight excluding the first digit), you can use [0-9]{1,8} or \d{1,8}.

For a decimal point, use \..

For two more numbers, use \d{2}.

So to add these together, /[1-9]\d{1,8}\.\d{2}/ should work.

However, you could also achieve similar functionality by avoiding using Regex altogether - this answer may help.

Community
  • 1
  • 1
Donald
  • 1,120
  • 12
  • 21
  • 1
    think it should be `/[1-9]\d{1,8}\.\d{2}/`, otherwise `1111111111.10` is a valid match which has 10 digits before decimal point. – shakib Jan 18 '16 at 19:05
  • @Donald I have tried your'e solution, however I am now unable to type anything into the textbox. Here is my JSFiddle: http://jsfiddle.net/Fn9cy/557/, could you please take a look at it just to see if I am going wrong some where? – Parandeep Singh Jan 18 '16 at 19:23
  • @ParandeepSingh I took a look at your JSFiddle, and what's happening is that every time a key is pressed, it is validating that key against the Regex - the Regex if for the full string, i.e. `10.99`, so just pressing `1` and then validating against the Regex will cause it to fail. I'm sure there's a way you could get this to work using JavaScript and a regex but I'd recommend you try achieving the same thing using `type`, `min`, `max` and `step` keywords on the `` tag itself and avoiding the JS solution altogether. – Donald Jan 18 '16 at 19:28
  • If you wanted to continue to continue the JavaScript approach, it might be easier to validate the input after the user has entered an input, such as: http://jsfiddle.net/hL4twnsp/. [Here's another similar question.](http://stackoverflow.com/questions/8825672/numeric-validation-with-regexp-to-prevent-invalid-user-input) – Donald Jan 18 '16 at 19:40