验证带有2个小数点的浮点形式的输入表单
Validate inputform for float with 2 decimal
我想用Javascript检查用户在html中输入的带有2个小数点的浮点值。只允许使用0-9和1 x","。如果没有",",我想插入",00"。
例如:
1234->1234,00
123f->123,00
1234,12->1234,12
123a4,15->1234,15
12341525,23->12341525,23
很好的是增加一个分离器4000,但有很好
12341525,23->12.341.525,23
正因为如此,我不能使用:
<input type="number" name="abc" step="0.01">
这将检查逗号是否多于一个。如果逗号后面没有逗号或数字不够,它将添加逗号和零。它还检查分数部分和积分部分是否为数字。
x = document.getElementById("abc").value;
if(x.indexOf(",") != x.lastIndexOf(",")) {
//Invalid, there is more than one comma
} else {
var comma = x.indexOf(",");
if(comma == -1) {
x = x.concat(",00"); // No comma
} else if(comma == x.length - 1) {
x = x.concat("00"); // comma, no digits after it though
} else if(comma == x.length - 2) {
x = x.concat("0"); // comma with 1 digit after it
}
if(comma <= x.length - 3) {
var parts = x.split(",");
if(isNaN(parts[0]) || isNaN(parts[1])) {
//Invalid, either the integral part or the fractional part is not a number
}
} else {
// Invalid, the comma comes before more than two digits
}
}
我认为这段代码正是您想要的。它还设置了一千个分隔符。
请注意,十进制分隔符通常是一个点,千位分隔符通常为逗号。;)
也许有一种较短的方法只使用正则表达式。。。但是下面的代码是有效的。
<input id="foo" type="text" onchange="formatNumber();" onkeyup="onlyNumbers();">
<script>
function formatNumber(){
// define separators
thousandSep=".";
decimalSep=",";
// get the input
n=document.getElementById("foo").value;
// Format decimals
n=parseFloat(n).toFixed(2);
decimals=decimalSep+n.substr(n.length-2);
// Temporarly remove the decimals and count how many thousand groups there is
n=parseInt(n).toString();
thousandGroups=parseInt(Math.ceil(n.length/3));
//Place the thousand separator between each group of 3 digits
for(i=1;i<thousandGroups;i++){
j=i-1;
n=n.substr(0,n.length-(3*i+j))+thousandSep+n.substr(n.length-(3*i+j));
}
// return the formated number
document.getElementById("foo").value=n+decimals;
}
function onlyNumbers(){
n=document.getElementById("foo").value;
// Check if last keyboard input is a digit... Accepts dots
if(n.substr(n.length-1).search(/^['d'.]/i)!=-1){
document.getElementById("foo").value=n;
}else{
document.getElementById("foo").value=n.substr(0,n.length-1)
}
}
</script>
相关文章:
- Nodejs服务器在解析之前生成输入表单
- 如何创建打开警报框的输入表单
- JavaScript onChange 事件侦听器对输入表单不起作用
- 如何在 OnKeyPress 事件后获取输入表单元素的值
- 单输入表单 - 特殊情况 |停止表单提交
- 需要输入表单验证
- 如何在谷歌图表中使用输入表单值
- 使用jquery可交换地更改两个html输入表单值
- 当从jqueryajax调用输入表单时,它不起作用
- 控制器作为搜索输入表单的语法
- 删除带有按钮的输入表单失败
- 验证带有2个小数点的浮点形式的输入表单
- AngularJS:输入表单在分部中不起作用
- 如何从php中的输入表单调用Javascript函数,以更改HTML
- 输入表单中的Sharepoint javascript
- 当点击输入表单时,为Raphael制作的对象添加光晕
- 当用户将数据输入表单时要知道的事件
- 保存输入表单后ImageMap颜色更改
- 链接输入表单中的填充脚本
- 有关多个输入表单验证的问题