Js 小数验证函数代码(基于正则)
程序员文章站
2022-06-22 14:32:16
(1)onkeypress 事件验证 用来验证输入操作 复制代码 代码如下: function onkeypressvalidate(obj, event, len) {...
(1)onkeypress 事件验证 用来验证输入操作
function onkeypressvalidate(obj, event, len) {
var e = window.event || event;
var key = e.keycode ? e.keycode : e.which;
var selectedtext = "";
if (window.getselection) {
var st = obj.selectionstart;
var ed = obj.selectionend;
selectedtext = obj.value.substring(st, ed);
} else if (document.selection) {
selectedtext = document.selection.createrange().text;
}
if (selectedtext != null && selectedtext != "") {
return true;
}
var dot = obj.value.indexof(".");
len = (typeof (len) == "undefined") ? 2 : len;
if (window.event) {
}
else {
if (key == 8 || key == 9 || key == 46 || (key >= 37 && key <= 40))//for firefox
return true;
}
if (key <= 57 && key >= 48) {
if (dot == -1)
return true;
else if (obj.value.length <= dot + len)
return true;
} else if ((key == 46) && dot == -1) {
return true;
}
return false;
}
(2)onblur 事件验证 用来验证最终的数据
function onblurvalidate(obj, messageid) {
var tempvalue = trim(obj.value);
var message = document.getelementbyid(messageid);
if (tempvalue == "") {
messageshow("", message, false);
return true;
}
else {
var regu = /^(\d+)(\.?)(\d{0,2})$/;
var re = new regexp(regu);
if (!re.test(tempvalue)) {
messageshow("number must be in this format (###.##) or (###)", message, true);
return false;
}
else {
messageshow("", message, false);
return true;
}
}
}
复制代码 代码如下:
function onkeypressvalidate(obj, event, len) {
var e = window.event || event;
var key = e.keycode ? e.keycode : e.which;
var selectedtext = "";
if (window.getselection) {
var st = obj.selectionstart;
var ed = obj.selectionend;
selectedtext = obj.value.substring(st, ed);
} else if (document.selection) {
selectedtext = document.selection.createrange().text;
}
if (selectedtext != null && selectedtext != "") {
return true;
}
var dot = obj.value.indexof(".");
len = (typeof (len) == "undefined") ? 2 : len;
if (window.event) {
}
else {
if (key == 8 || key == 9 || key == 46 || (key >= 37 && key <= 40))//for firefox
return true;
}
if (key <= 57 && key >= 48) {
if (dot == -1)
return true;
else if (obj.value.length <= dot + len)
return true;
} else if ((key == 46) && dot == -1) {
return true;
}
return false;
}
(2)onblur 事件验证 用来验证最终的数据
复制代码 代码如下:
function onblurvalidate(obj, messageid) {
var tempvalue = trim(obj.value);
var message = document.getelementbyid(messageid);
if (tempvalue == "") {
messageshow("", message, false);
return true;
}
else {
var regu = /^(\d+)(\.?)(\d{0,2})$/;
var re = new regexp(regu);
if (!re.test(tempvalue)) {
messageshow("number must be in this format (###.##) or (###)", message, true);
return false;
}
else {
messageshow("", message, false);
return true;
}
}
}