Js 小数验证函数代码(基于正则)
编程学习 2021-07-05 10:07www.dzhlxh.cn编程入门
经常需要使用JS来验证一些数字(OnKeyPress 事件和onblur事件来验证),写了两个事件来验证,验证了一般情况。
(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;
}
}
}