javascriptjqueryvalidation

How to validate a decimal value input?


Currently working on only decimal values where in the text field user enter only deciaml value. Should accept only 10 numbers for example if user enter 12345.000000 it should get an alert says Number field format error. Please re-enter using the proper format. (6.3)

With my current jquery code it will accept decimal value

$("#txtQty").keyup(function() {
var $this = $(this);
$this.val($this.val().replace(/[^\d.]/g, ''));        
});

This is my html code for the text box with this html it will allow only 10 character

<input id="txtQty" type="text" maxlength="10"/>

I tired the below SO user told but still I am getting the same issue

   $('#txtQty').focusout(function(e) {
   if('123456.789'.match(/^[0-9]{6}\.[0-9]{3}$/) !== null){
      alert("Number field format error. Please re-enter using the proper format. (6.3)");  
   }else{
       '123456.7890'.match(/^[0-9]{6}\.[0-9]{3}$/) !== null
   }
});

before decimal point it has to accept (1-6) 6 number after decimal point it has to accept 3 only zero's if wrongly typed it should throw an alert not at all working still not getting that

Here is the fiddle link for the same

123456.000 -- true
12345.000 -- true
1234.000 -- true
123.000 -- true
12.000 -- true
1.000 -- true

Thanks in advance

$('.ipt_Havg').focusout(function (e) {
var regexp = /\d*\.\d{3}/
if (document.getElementById("ipt_Havg").value !== regexp) {
    alert("Number field format error. Please re-enter using the proper format. (6.3)");
} else {
    alert('nothing wrong here');
}
});

Solution

  • You can specify repetitions in RegExps:

    '123456.789'.match(/^[0-9]{6}\.[0-9]{3}$/) !== null
    true
    '123456.7890'.match(/^[0-9]{6}\.[0-9]{3}$/) !== null
    false