如何验证小数值输入?

时间:2015-11-16 13:37:39

标签: javascript jquery validation

目前只处理十进制值,在文本字段中用户只输入deciaml值。应该只接受10个数字,例如,如果用户输入12345.000000,它应该收到警告,说数字字段格式错误。请使用正确的格式重新输入。 (6.3)

使用我当前的jquery代码,它将接受十进制值

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

这是我用html文本框的html代码,它只允许10个字符

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

我厌倦了下面的SO用户告诉我,但我仍然遇到同样的问题

   $('#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
   }
});

在小数点之前它必须接受(1-6)小数点后的6位数它必须接受3只有零如果错误输入它应该抛出一个完全没有工作的警报

以下是同一

fiddle link

123456.000 - 真实 12345.000 - 真实 1234.000 - 真实 123.000 - 真实 12.000 - 真实 1.000 - 真实

提前致谢

$('.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');
}
});

4 个答案:

答案 0 :(得分:3)

1)你的if / else被破坏了......

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 // <- comparison makes no sense here
}

您错误地使用比较运算符代替else中的“语句”。 else需要包含“声明”(要做的事)而不是其他比较运算符。

请参阅:MDN "if...else" documentation

如果某些条件为真,则执行某些操作,否则执行其他操作。

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 {
   alert('nothing wrong here');
}

2)注意:我以前认为这太明显了,甚至没有提到,但是,你已经将'123456.789'硬编码到条件中。换句话说,输入表单的价值永远不会重要......

'123456.789'.match(/^[0-9]{6}\.[0-9]{3}$/)始终为true,因为'123456.789'是此处使用的唯一值。

否则,请使用字段的值...

$('#ipt_Havg').val().match(/\d*\.\d{3}/) !== null

3)你的逻辑也是倒退的。

if ($('#ipt_Havg').val().match(/\d*\.\d{3}/) !== null) {
    alert('nothing wrong here');
} else {
    alert("Number field format error. Please re-enter using the proper format. (6.3)");
}

DEMO:http://jsfiddle.net/wfzv0h5y/

4)正则表达式错误...

  

但是最后一个小错误它只能接受三个零不超过但现在如果我输入1234.0000仍然接受

你的正则表达式还需要修复......

^\d{1,6}\.0{3}$

DEMO:http://jsfiddle.net/wfzv0h5y/6/

答案 1 :(得分:0)

JQuery Number Formatter插件在您的情况下是一个很好的选择。

https://github.com/andrewgp/jsNumberFormatter

您可以通过此检查输入并验证您想要的方式。

答案 2 :(得分:0)

您可以使用HTML5输入号码:

<input type='number' step='0.001' max="999999.999" />

step=设置小数位,max=保证另一方。

答案 3 :(得分:-1)

您可以在RegExps中指定重复:

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