var isIE = (navigator.appVersion.indexOf("MSIE") != -1) ? true : false;
//验证控件
var Validator = function(formid) {
var $$ = function(id) {
return document.getElementById(id);
}
var base = this;
var form = $$(formid);
var validArr = new Array();
var validObjTag = "v_";
//绑定验证控件的Class属性
var spans = document.getElementsByTagName("span");
for (var i = 0; i < spans.length; i++) {
if (spans[i].id.indexOf(validObjTag) != -1)
spans[i].className = "validator";
}
//绑定提交事件
form.attachEvent("onsubmit", function() {
return base.valid();
});
// form.onsubmit = function() {
// return base.valid();
// }
//验证控件对应的ID
function validObjID(id) {
return validObjTag + id;
}
//绑定验证事件
this.bind = function(id, eventArr, afterFun) {
if (!$$(validObjID(id))) {
var valid = validObjID(id);
var span = document.createElement("span");
span.setAttribute("id", valid);
span.setAttribute("class", "validator");
$$(id).insertAdjacentElement("afterEnd", span);
//alert("验证控件(id=" + validObjID(id) + ")不存在!");
}
var count;
validArr.push(new Array(id, eventArr, afterFun));
if (isIE) {
$$(id).attachEvent("onblur", function() {
var result = true;
for (var i = 0; i < eventArr.length; i++) {
result = base.doValid(id, eventArr[i][0], eventArr[i][1], eventArr[i][2]);
if (!result) {
break;
}
}
if (afterFun != null && afterFun != undefined && result) {
afterFun($$(id), $$(validObjID(id)));
}
});
} else {
$$(id).addEventListener("blur", function() {
var result = true;
for (var i = 0; i < eventArr.length; i++) {
result = base.doValid(id, eventArr[i][0], eventArr[i][1], eventArr[i][2]);
if (!result) {
break;
}
}
if (afterFun != null && afterFun != undefined && result) {
afterFun($$(id), $$(validObjID(id)));
}
}, false);
}
}
//所有对象的验证事件
this.valid = function() {
var pass = true;
for (var i = 0; i < validArr.length; i++) {
var result = false;
for (var j = 0; j < validArr[i][1].length; j++) {
result = base.doValid(validArr[i][0], validArr[i][1][j][0], validArr[i][1][j][1], validArr[i][1][j][2]);
if (!result) {
pass = false
break;
}
}
var afterFun = validArr[i][2];
if (afterFun != null && afterFun != undefined && result) {
afterFun($$(validArr[i][0]), $$(validObjID(validArr[i][0])));
}
}
return pass;
}
//一个对象的验证事件
this.doValid = function(id, type, msg, reg) {
switch (type) {
case "empty": //为空
return writeMsg(id, msg, ($$(id).value == ""));
break;
case "regular": //正则验证
return writeMsg(id, msg, !reg.test($$(id).value));
break;
case "contrast":
return writeMsg(id, msg, ($$(id).value != $$(reg).value));
break;
//在此添加别的判断事件
}
}
//写出错误信息
function writeMsg(id, msg, result) {
if (result) {
$$(validObjID(id)).innerHTML = msg;
return false;
} else {
$$(validObjID(id)).innerHTML = "";
return true;
}
}
}
//例子
window.onload = function() {
var vld = new Validator("form1");
vld.bind("txt_pwd", [["empty", "*"], ["regular", "超过最大长度10", /^.{0,10}$/], ["contrast", "不相同", "txt_pwd2"]], afterFun);
}
function afterFun(txt, msg) {
}
empty:空值;regular:正则验证;contrast:两控件值对比