当前位置:Gxlcms > 正则表达式 > Js 小数验证函数代码(基于正则)

Js 小数验证函数代码(基于正则)

时间:2021-07-01 10:21:17 帮助过:32人阅读

(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;
}
}
}

人气教程排行