如何使用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;
}
}
}
编辑:
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);
最佳答案
你可以尝试这样的事情:
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);
该代码不兼容跨浏览器,但它应该为您提供如何完成此操作的提示。
<小时/>更新:不使用input事件。
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);
关于javascript - 使用 javascript 验证文本框中具有十进制值的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9908947/