Skip to content

Instantly share code, notes, and snippets.

@mingyun
Created January 16, 2014 03:16
Show Gist options
  • Save mingyun/8449253 to your computer and use it in GitHub Desktop.
Save mingyun/8449253 to your computer and use it in GitHub Desktop.
核心代码不足50行的表单验证,支持ajax验证和表单验证,支持自定义规则和自定义提醒样式http://www.oschina.net/code/snippet_1015196_32669
/*
* @author duansong
* @email [email protected]
* @date 2014-1-14
* @descrition 基于jquery的表单验证组件,支持ajax验证
*/
(function($,window){
//配置文件
var settings = {
//验证规则
rules:{
required:{
message:"该字段必须填写",
rule:"\\S+"
},
number:{
message:"只能输入数字",
rule:"^\\d*$"
},
chinese:{
message:"只能输入中文字符",
rule:"^[\\u4e00-\\u9fa5]*$"
},
email:{
message:"请输入一个正确的邮箱地址",
rule:"\\w+([-+\\.]\\w+)*@\\w+([-\\.]\\w+)*\\.\\w+([-\\.]\\w+)*"
},
url:{
message:"请输入一个正确的url",
rule:"[a-zA-z]+://[^\\s]*"
},
phone:{
message:"请输入一个正确的电话号码",
rule:"\\d{3}-\\d{8}|\\d{4}-\\d{7}|\\d{11}"
},
zipcode:{
message:"请输入一个正确的邮政编码",
rule:"[1-9]\\d{5}(?!\\d)"
},
identificate:{
message:"请输入一个正确的身份证号码",
rule:"\\d{15}|\\d{18}"
},
range:{
message:"只能输入{0}-{1}位数字",
rule:"^\\d{{0},{1}}$"
},
price:{
message:"请输入有效的价格",
rule:"^[0-9]+(\\.[0-9]{1,2})?$"
}
},
/*
* @param isPass是否通过验证
* @message 未通过验证的提示信息
* */
placeholder:function(isPass,message){
if(isPass){
var error = $(this).next(".valid-error");
error.length&&$(this).next(".valid-error").remove();
$(this).removeClass("el-valid-error");
}else{
$(this).addClass("el-valid-error");
var error = $(this).next(".valid-error");
if(!error.length){
$(this).after("<label class='valid-error'></label>");
error = $(this).next(".valid-error");
}
error.text(message);
}
}
};
//字符串format
//例如"我是{11}"
//如果只传入source,则返回11(数组)
//如果传入source,params,则替换{}中内容
var format = function(source,params){
if(typeof params =="undefined"){
var params = [];
var b = source.match(/\{+(\S+?)\}+/g);
b = $.map(b,function(n){
return n.replace(/\{|\}/g,"");
});
return b;
}else{
params = $.isArray(params)?params:[params];
$.each(params, function( i, n ) {
source = source.replace( new RegExp("\\{" + i + "\\}", "g"), n);
});
return source;
}
}
//检查元素属性是否通过验证
var check = function(el,rules){
var val = $(el).attr("data-valid").split(";");
var errorMsg = "",isPass=true;
for(var i=0,max=val.length;i<max;i++){
if(val[i]=="")continue;
v=val[i].split(":");
var para = [];
if(v.length>1){
para = format(v[1]);
}
var rule= format(rules[v[0]]["rule"],para);
var value = $(el).val();
if(!new RegExp(rule).test(value)){
if(v[0]!=="required"&&value==""){
continue;
}else{
errorMsg = format(rules[v[0]]["message"],para);
isPass = false;
break;
}
}else{
continue;
}
}
return {isPass:isPass,errorMsg:errorMsg};
}
//定义扩展方法,用于特殊扩展的处理
var extend = function(oObj,nObj){
var result ={};
$.extend(result,oObj);
if($.isPlainObject(nObj)){
$.each(nObj,function(n,v){
if(n=="rules"){
$.extend(result.rules,nObj.rules);
}else{
result[n] = nObj[n];
}
});
}
return result;
}
var Valid = function(node,opts){
var setting = extend(settings,opts);
var $formNode = $(node);
var valid = true;
$("[data-valid]",$formNode).each(function(){
var result = check(this,setting.rules);
if(result.isPass===false){
valid = false;
}
setting.placeholder.call(this,result.isPass,result.errorMsg);
});
$formNode.delegate("[data-valid]","blur",function(){
var result = check(this,setting.rules);
setting.placeholder.call(this,result.isPass,result.errorMsg);
});
return valid;
}
var Validate = function(node,opts){
var setting = extend(settings,opts);
var $formNode = $(node);
$formNode.submit(function(){
return Valid($formNode,opts);
});
}
//对外接口
$.extend($.fn,{
//一般用于表单验证
validate:function(opts){
return this.each(function(){
Validate(this,opts);
});
},
//一般用于ajax验证,callback回调函数
valid:function(opts,callback){
if($.isFunction(opts)&&typeof callback =="undefined"){
callback = opts;
opts = {};
}
return this.each(function(){
var isPass = Valid(this,opts);
$.isFunction(callback)&&callback.call(window,isPass);
});
}
});
})(jQuery,window)
//css
.el-valid-error{border:1px solid #B92C28}
.valid-error{color:#B92C28;font-size:12px}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment