[英]Validation of numbers with decimal values in textbox using javascript
how to restrict user to enter only numbers with 6 digits and two decimal values in textbox using javascript?? 如何限制用户在使用JavaScript的文本框中仅输入6位数字和两个十进制值的数字?
//Function to allow only numbers to textbox
function validate(key) {
//getting key code of pressed key
var keycode = (key.which) ? key.which : key.keyCode;
var phn = document.getElementById('txtPhn');
//comparing pressed keycodes
if ((keycode < 48 || keycode > 57)) {
return false;
} else {
if (phn.value.length < 6) {
return true;
} else {
return false;
}
}
}
EDIT: 编辑:
var txtBudget = document.getElementById('MainContent_txtBudget');
txtBudget.addEventListener('input', function (prev)
{
return function (evt) {
if (!/^\d{0,6}(?:\.\d{0,2})?$/.test(this.value)) {
this.value = prev;
}
else {
prev = this.value;
}
};
} (txtBudget.value), false);
You can try something like this: 您可以尝试如下操作:
var foo = document.getElementById('foo');
foo.addEventListener('input', function (prev) {
return function (evt) {
if (!/^\d{0,6}(?:\.\d{0,2})?$/.test(this.value)) {
this.value = prev;
}
else {
prev = this.value;
}
};
}(foo.value), false);
The code is not cross-browser compliant, but it should give you a hint of how it can be done. 该代码不兼容跨浏览器,但是应该给您一些提示。
demo: http://jsfiddle.net/v4tGc/ 演示: http : //jsfiddle.net/v4tGc/
Update : not using the input event. 更新 :不使用输入事件。
var foo = document.getElementById('foo');
foo.addEventListener('keypress', function (evt) {
var value = this.value + String.fromCharCode(evt.which);
if (!/^\d{0,6}(?:\.\d{0,2})?$/.test(value)) {
evt.preventDefault();
}
}, false);
**When I Googling, found a code. And then i modify to what i need. And I think it will help you**.
**HTML**
<html>
<head>
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<body>
<input type="text" id="sal" name="sal" onkeypress="return isDecimalNumber(event,this)">
</body>
</html>
**Javascript**
<script type="text/javascript">
function isDecimalNumber(evt, c) {
var charCode = (evt.which) ? evt.which : event.keyCode;
var dot1 = c.value.indexOf('.');
var dot2 = c.value.lastIndexOf('.');
if (charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57))
return false;
else if (charCode == 46 && (dot1 == dot2) && dot1 != -1 && dot2 != -1)
return false;
return true;
}
</script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.