Arun Mahajan
Arun Mahajan

Reputation: 41

How to restrict from entering any number with max 2 digits before and 8 digits after decimal in jquery

I am trying to check the number of digits before and after a decimal and total number of digits in a on("keypress keyup blur",function (event)) function in jquery. It doesn't work for me.

I have an input element in my html code where a user is suppose to enter:

I tried to make below regular expression for this /^\d{0,2}(.\d{0,8})?$/

It seems quite OK to me but when I tried it with jquery in my code it fails and allow a user to enter more than 2 digits before decimal

$("#longitude").on("keypress keyup blur",function (event) {  
  $(this).val($(this).val().replace(/[^\d\.].+/, ""));
    if ((event.which < 46 || event.which > 57) || $(this).val().length>9 || $(this).val()===/^\d{0,2}(\.\d{0,8})?$/) {
      event.preventDefault();
    }
  });

I want it should not allow to press a key after two digits, if decimal is not there, while typing itself. If user puts a decimal it should allow further 8 digits

valid strings(Min 0 and Max before decimal and min 0 and max 8 after decimal and decimal is optional):

Invalid strings are

Upvotes: 0

Views: 1145

Answers (2)

The fourth bird
The fourth bird

Reputation: 163217

Instead of checking the numbers of event.which you might use a single regex instead while typing to correct the input when something is entered that does not fit the required structure. Then when that occurs you could replace the wrong input with the last know valid input.

Note that you want to allow 0-2 digits, a dot and 0-8 digits which are 11 characters at max, so I think this $(this).val().length>9 should be 11.

As the previous pattern also allows a single dot at the end, you might when for example submitting a form, check the final value using this regex which checks if the value is either a 1-2 digits followed by a dot and 1-8 digits or | a dot and 1-8 digits and does not accept an empty string.

^(?:\d{1,2}(\.\d{1,8})?|\.\d{1,8})$

Regex demo

let lastValid = "";
$("#longitude").on("keypress keyup blur", function(event) {
  if (/^\d{0,2}(?:\.\d{0,8})?$/.test($(this).val())) {
    lastValid = $(this).val();
  } else {
    event.preventDefault();
    $(this).val(lastValid);
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="" name="">
  <input type="text" value="" id="longitude">
</form>

Upvotes: 1

Anu Viswan
Anu Viswan

Reputation: 18155

You could use following.

^[0-9]{0,2}([.][0-9]{0,8})?$

Example,

Try it here

Upvotes: 0

Related Questions