Skip to content
Advertisement

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

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

Advertisement

Answer

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

Advertisement