Js 小数验证函数代码(基于正则)
(编辑:jimmy 日期: 2024/11/16 浏览:3 次 )
(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;
}
}
}
下一篇:JavaScript 正则表达式验证函数代码