0

I am new to javascript. I want to validate input box value it should allow integer and decimal value (no alphabets), no limit for integer value but for decimal value it should accept only two digit after decimal point. https://jsfiddle.net/pnd6yvbj/ Example:

Allowed values in and decimal

1.1
1.12
233

Not allowed more than two decimal point

1.121

What I tried:

<input type="text" id="txt" value="" onkeyup = "check_val($(this).val())"/>

<script>
function check_val(val) {
      var val = val.replace(^[1-9]\d*(\.\d+)?$,"");
       $("#txt").val(val.split('  ').join(' '));
    }
</script>
faiz
  • 1
  • 1
  • The pattern should be like this to match an optional dot and 1-2 digits `^[1-9]\d*(?:\.\d{1,2})?$` https://regex101.com/r/unspdE/1 – The fourth bird Oct 21 '20 at 07:12
  • @Thefourthbird getting error Unexpected token '^' – faiz Oct 21 '20 at 07:25
  • The pattern should be between forward slashes `val.replace(/^[1-9]\d*(?:\.\d{1,2})?$/, "");` – The fourth bird Oct 21 '20 at 07:31
  • @Thefourthbird please check jsfiddle which https://jsfiddle.net/pnd6yvbj/ if character insert then it should replace with empty but it is not working. – faiz Oct 21 '20 at 07:36
  • This is not a good approach to sanitize string input, try `val = val.replace(/^([1-9]\d*(?:\.\d{0,2})?)?.*$/, "$1");` and you will see if you type `.` anywhere in the already input value. – Wiktor Stribiżew Oct 21 '20 at 11:14

0 Answers0