统一的表单验证(jquery+正则)

表单验证一直很繁琐,特别是大点的表单,如果每个input都去单独写验证简直要写死人,最近写了一小段js统一的验证表单内容是否正确。

使用这段代码就不再需要对每个input写格式判断,只需要将正确格式的正则表达式写在datatype里就可以了,提交表单按钮也只需要绑定checkForm函数就可以了。

大家有什么建议可以评论一下

<input type="text" datatype=“正则”/>

//作者www.cumt.top

//表单验证

//点击下一步事件
function checkForm(form){
var success = true;
$("."+form+" input").each(function(){
var $that = $(this);
var dataType = eval($that.attr("dataType"));
if(dataType!=undefined){
if($that.val().match(dataType)){
$that.removeClass("borderRed");
}else{
$that.focus();
$that.addClass("borderRed");
success = false;
return false;
}
}
})
return success;
}

//给每个带有datatype属性的标签绑定blur focus事件
//引用请注明http://www.cumt.top/blog/?p=76

$(document).on("blur","input",function(){
var $that = $(this);
var dataType = eval($that.attr("dataType"));
if(dataType!=undefined){
if($that.val().match(dataType)){
$that.removeClass("borderRed");
}else{
$that.addClass("borderRed");
}
}
})
$(document).on("focus","input",function(){
$(this).removeClass("borderRed");
});

引用请注明http://www.cumt.top/blog/?p=76

posted @ 2015-09-19 21:26  冥冥之罪  阅读(1197)  评论(1编辑  收藏  举报
马洪斌空间