0

I need a regex which matches an inputs like: 1234.789 12 123.02

that is, maximum 4 digits on the left side of . and maximum 3 on right of .

here is what I have tried.

i = 0;
$(document).ready(function(e){
    $("input").keypress(function(e){
         var patt = new RegExp("^[0-9]{1,4}(?:\.[0-9]{0,3})?$");
         var val = this.value + e.key;
         debugger;
    if (!patt.test(val)){
     e.preventDefault();
    }
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Enter your name: <input type="number">
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
blueMoon
  • 2,831
  • 2
  • 13
  • 10
  • Double escape special chars in the constructor notation. See [Why do regex constructors need to be double escaped?](http://stackoverflow.com/questions/17863066/why-do-regex-constructors-need-to-be-double-escaped) However, use a regex literal: `var patt = /^\d{1,4}(?:\.\d{0,3})?$/;` – Wiktor Stribiżew Jan 04 '17 at 17:15
  • 1
    Is there a problem with the code you tried? If yes, what is it? – Felix Kling Jan 04 '17 at 17:16
  • 1
    The regex is working fine, I think, the problem is how you are trying to restric the values. Doing `e.preventDefault();` will not cause to "undo" – Pablo Matias Gomez Jan 04 '17 at 17:17

1 Answers1

0

This should do :

^\d{0,4}(\.\d{0,4}){0,1}$

You can check in the below:

Regular Expression

Buddy
  • 10,874
  • 5
  • 41
  • 58
Ranadip Dutta
  • 8,857
  • 3
  • 29
  • 45