如何validation十进制值输入?
目前仅处理十进制值,在文本字段中用户只输入deciaml值。 应该只接受10个数字,例如,如果用户输入12345.000000,它应该得到一个警告说数字字段格式错误。 请使用正确的格式重新输入。 (6.3)
使用我当前的jquery代码,它将接受十进制值
$("#txtQty").keyup(function() { var $this = $(this); $this.val($this.val().replace(/[^\d.]/g, '')); });
这是我用html文本框的html代码,它只允许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只有零如果错误输入它应该抛出一个警报根本没有工作仍然没有得到那个
这是相同的小提琴链接
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'); } });
您可以在RegExps中指定重复:
'123456.789'.match(/^[0-9]{6}\.[0-9]{3}$/) !== null true '123456.7890'.match(/^[0-9]{6}\.[0-9]{3}$/) !== null false
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”文档
如果某些条件成立,则执行某些操作,否则执行其他操作。
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)"); }
演示: http : //jsfiddle.net/wfzv0h5y/
4)正则表达式错误...
但是最后一个小错误它只能接受三个零不超过但现在如果我输入1234.0000仍然接受
你的正则表达式也需要修复......
^\d{1,6}\.0{3}$
演示: http : //jsfiddle.net/wfzv0h5y/6/
在您的情况下,JQuery Number Formatter插件是一个不错的选择。
https://github.com/andrewgp/jsNumberFormatter
您可以通过此检查输入并validation您想要的方式。
您可以使用HTML5输入数字:
step=
设置小数位, max=
保证另一方。