0

How to Validate input numbers with only 2 digits and allow users to enter point numerals using JQuery?

Users can enter 0 to 99 numerals and point numerals

such as (

0.1 (3 digits)

3.14 (4 digits)

98.121212121786234435243 (more digits)

etc......)

https://jsfiddle.net/kwcft9bq/

<!DOCTYPE html>
<html>
<body>
<form id="submit_form" method="post">
<input type='number' id="name" name='number' min="0" required><br>    
 <input type="submit" text="Submit" >
</form>
     

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/jquery-validation@1.19.3/dist/jquery.validate.min.js"></script>
<script>
    $(document).on('input', "#number", function () {
        
     if ($(this).val().length > 2) {
         $(this).val($(this).val().slice(0, 2));
     }
});
</script>
</body>
</html>

I try to use

if($(this).val() == "0." || $(this).val() == "1." .....|| $(this).val() == "98."){
  //can input more digits after "points"  ->  .
 }

but finally not work

any idea??? Thank you

JessciaLau
  • 95
  • 10
  • 1
    Does this answer your question? [Allow 2 decimal places in ](https://stackoverflow.com/questions/34057595/allow-2-decimal-places-in-input-type-number) – DecPK Aug 31 '21 at 03:27

1 Answers1

1

you can use regex to validate that pattern:

$(document).on('input', "#number", function() {
    var regex = /^\d{0,2}(\.\d+)?$/;
    var value = $(this).val();
    if (!regex.test(value)) {
       $(this).val(parseFloat(value.slice(0, 2) + "." + value.slice(2)));
    }
  });

You can check it here

Canh
  • 516
  • 1
  • 3
  • 9
  • Thank you very much, your code works perfectly, but one more question, Is it possible to sub the zero after the point?? for example,I would like to enter 22.1 , but it displays 22.01, I need to delete the 0 manually. Thanks – JessciaLau Aug 31 '21 at 04:34