user3477172
user3477172

Reputation: 79

Javascript or Jquery - restricting input field to only 8 decimals

Is it possible to restrict a form field in HTML with Jquery/Javascript to only 3 decimals . What I mean is that: 33.334 should be allowed as input 3.344 & 444444.556 etc. as well but it should not allow 5.6664 etc.

How can I do that?

Upvotes: 1

Views: 240

Answers (1)

Amit Joki
Amit Joki

Reputation: 59292

You don't need jQuery to do that. Just use pattern attribute of <input> like this

<input type="text" pattern="^\d+\.\d{0,3}$">

The above would work on most browsers but if you want to support some old browsers, you would bind that <input> on a key-based event and check for the value using the above regex and restricting the user input.

$('input').on('blur', function () {
    if (!/^\d+\.\d{0,3}$/.test($(this).val())) {
        alert("Must be a number upto 3 decimals!");
    }
});

DEMO

Press Enter to see pattern in action. Click elsewhere to see jQuery in action

Upvotes: 2

Related Questions