自定义的javascript的验证框架

看过 jquery 验证框架,在使用的时候,其实还是很晕的,很麻烦,使用的时候代码也不简洁,因此才有了弄一个自己的jquery验证框架的计划,基本原理就是对 input ,select, textarea 这三类控件做校验,在里面定义自定义属性作为检验。 另外采用js 做i18n 国际化,通过cookies 中的语言,调用不同的js 语言包, 对于自己开发项目来说,足够用了,而且,还可以灵活扩展。个人用应该不错。

为了测试这个验证框架,其实静态html 页面足够了,但习惯问题,自己搭建了一个简单的 动态web  工程,后面会给出源代码下载


1. 验证框架主要采用 jquery异步对象去扩展的,也就是jquery defered 的用法,这样去做验证的好处是,即使某些验证是采用ajax 方式去验证的,结合jquery when 函数,一样可以批量校验. 主要代码如下:
程序代码 程序代码

function Validator(errorHandle){
    this.errorHandle = errorHandle;
    this.elements = ["input","select","textarea"];
}

Validator.prototype = {
        contructor : Validator,
        rules : {},
        addRules : function(ruleName, validFunction, errorFunction){
            this.rules[ruleName] = {
                    validFunction : validFunction,
                    errorFunction : errorFunction
            };
        },
        
        eventFunction : function(item){
            var self = this;
            $(item).die().live("blur", function(){
                self.validateItem(item);    
            });
        },
        
        bindingEvent : function(divId){
            var self = this;
            
            self.elements.forEach(function(element){
                $("#" + divId).find(element).each(function(i, item){
                    self.eventFunction(item);        
                });
            });
            
        },
        
        validateDiv : function(divId){
            var dtdList = [],
                self = this;
            
                self.elements.forEach(function(element){
                    $("#" + divId).find(element).each(function(i, item){
                        dtdList.push( self.validateItem(item) );
                    });                    
                });
            
                self.elements.forEach(function(element){
                    if ($("#" + divId).find(element).length == 0){
                        var deferred = $.Deferred();
                        deferred.resolve();
                        dtdList.push(deferred);
                    }                
                });
            
            return $.when.apply(null, dtdList).fail(function(){
                if(self.errorHandle) {
                    self.errorHandle.call(null, divId);                    
                }
            });
            
        },
        
        validateItem : function(d){
            var self = this;
            var ruleList = [];
            for(var r in this.rules){    
                if( $(d).is("[" + r + "]") ){
                    ruleList.push(r);
                }
            }
            var dtd = $.Deferred();
            var checked = function(){    
                if ( ruleList.length >= 1 ){
                    var ok = self.validate(d, ruleList[0]);
                    ok.done(function(){
                        if(ruleList.length >= 2){
                            self.validate(d, ruleList[1]);
                        }
                        ruleList.shift();
                        checked();
                    }).fail(function(){
                        dtd.reject();
                    });
                } else {
                    dtd.resolve();
                } ;
                //dtd.resolve();
                //return dtd;
            };
            checked();
            return dtd;
            
        },
        validate : function(d, rule){
            var value = $(d).val(),
                attributeValue = $(d).attr(rule),
                f = this.rules[rule].validFunction,
                self = this;            
        
            var ok = f.call(null, d, value, attributeValue);
            
            return ok.fail(function(item){
                if($(item).siblings("[validationError]").length != 0 ){
                    $(item).siblings("[validationError]").remove();                            
                }
                if(self.rules[rule].errorFunction){
                    self.rules[rule].errorFunction(d, rule);
                }else {
                    self.showErrorMessage(d, rule);                    
                }
            }).done(function(item){
                if($(item).siblings("[validationError]").length != 0 ){
                    $(item).siblings("[validationError]").remove();                            
                }
            });
        },
        
        validationByRegx : function(d, value, regx){
            var dtd = $.Deferred(),
            ok = regx.test(value);
        
            if(ok || $.trim(value) === ""){
                dtd.resolve(d);
            } else {
                dtd.reject(d);
            }
            return dtd.promise();
        },
        
        /*默认的出错处理方法*/
        showErrorMessage : function(item,rule){
            var msgInfo = getJSLocale( $(item).attr("msgid") );
            var ruleInfo = getJSLocale( "msg_" + rule );
            if($(item).siblings("span").find("[msgid='msg_"+ rule +"']").length == 0){
                var message = msgInfo || ruleInfo;
                $(item).parent().append("<span validationError><label msgid='msg_" + rule +"'>" + message + "</label></span>");                
            }
        }
};

//add default rule
Validator.prototype.addRules("required", function(d, value, attributeValue){
    var dtd = $.Deferred();
    var ok = !($.trim(value) == "" || value == null);
    if(ok){
        dtd.resolve(d);
    } else {
        dtd.reject(d);
    }
    return dtd.promise();
});


Validator.prototype.addRules("maxLen", function(d, value, attributeValue){
    var dtd = $.Deferred();
    var ok = (value.length <= attributeValue);
    if(ok){
        dtd.resolve(d);
    } else {
        dtd.reject(d, attributeValue);
    }
    return dtd.promise();
    
}, function(d, rule){
    if($(d).siblings("span").find("[msgid='msg_" + rule + "']").length == 0){
        var attributeValue = $(d).attr(rule);
        var msgInfo = getJSLocale( $(d).attr("msgid"), {length:attributeValue} );
        var ruleInfo = getJSLocale( "msg_" + rule, {length:attributeValue} );
        var message = msgInfo || ruleInfo;
        $(d).parent().append("<span validationError><label msgid='msg_" + rule + "' errorMsgParam='"+attributeValue+"'>" + message + "</label></span>");                
    }
});

Validator.prototype.addRules("minLen", function(d, value, attributeValue){
    var dtd = $.Deferred();
    var ok = (value.length >= attributeValue);
    if(ok){
        dtd.resolve(d);
    } else {
        dtd.reject(d, attributeValue);
    }
    return dtd.promise();
    
}, function(d, rule){
    if($(d).siblings("span").find("[msgid='msg_" + rule + "']").length == 0){
        var attributeValue = $(d).attr(rule);
        var msgInfo = getJSLocale( $(d).attr("msgid"), {length:attributeValue} );
        var ruleInfo = getJSLocale( "msg_" + rule, {length:attributeValue} );
        var message = msgInfo || ruleInfo;
        $(d).parent().append("<span validationError><label msgid='msg_" + rule + "' errorMsgParam='"+attributeValue+"'>" + message + "</label></span>");                
    }
});

Validator.prototype.addRules("url", function(d, value, attributeValue){
    return Validator.prototype.validationByRegx(d, value, /^(((ht|f)tp(s?))\:\/\/)[a-zA-Z0-9]+\.[a-zA-Z0-9]+[\/=\?%\-&_~`@[\]\':+!]*([^<>\"\"])*$/i);
});

Validator.prototype.addRules("email", function(d, value, attributeValue){    
    return Validator.prototype.validationByRegx(d, value, /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/);
});

Validator.prototype.addRules("english", function(d, value, attributeValue){    
    return Validator.prototype.validationByRegx(d, value, /^[a-zA-Z0-9_\-]+$/);
});



对于html 页面的验证方式呢,采用如下方式:
程序代码 程序代码

<div><h1>自定义验证框架测试</h1></div>
   <div>    
       <div id="required_valid_div">
           <input type="text" required minLen="3" maxLen="5"/>   <p />
           english:<input type="text" required english maxLen="50"/>   <p />
           <input type="text" required maxLen="50"/>   <p />
           <input type="text" url required />   <p />
           email: <input type="text" email />   <p />
          
           <select required>
               <option value="">请选择</option>
               <option value="1">中国</option>
           </select>
           <p />
           <textarea required maxLeng="500"></textarea>  <p />
           自定义错误信息:<input type="text" url required msgid="myUrlError"/>   <p />        
       </div>
       <button onclick="javascript:validatorDiv();">验证</button>      
       <button onclick="javascript:loadI18nCN();">Load 中文国际化</button>
       <button onclick="javascript:loadI18NEN();">Load English i18N</button>
      
   </div>  


其中有很多自定义的属性,比如required,maxLen, url,email 等。 当然部分与HTML5的有冲突,也不矛盾。如果不想冲突,当然可以另外定义,但要注意validation.js 要同步修改,还有i18n 国际化文件. 在这里面我自定义了一个 自定义错误信息,如果有msgid 属性的会去找msgid 对应的国际化消息,否则会去找rule_加上自定义属性的消息. 这是为了自己的项目定制的。

js 国际化的支持
程序代码 程序代码

var JSLocale = {
    msg_required: "不能为空",
    msg_maxLen: "最大长度{{:length}}.",
    msg_minLen: "最小长度{{:length}}.",
    msg_url: "不合法的网址",
    msg_email: "Email 不合法",
    msg_english : "只允许输入 0-9,a-z, A-Z",
    myUrlError: "自定义错误提示:url 不合法哦",
    end: ""
};



测试效果


附上源代码下载:
下载文件 javascript validation framework source code


除非申明,文章均为一号门原创,转载请注明本文地址,谢谢!
文章来自: 本站原创
引用通告: 查看所有引用 | 我要引用此文章
Tags: JS validation
相关日志:
评论: 0 | 引用: 0 | 查看次数: -
发表评论
昵 称:
密 码: 游客发言不需要密码.
内 容:
验证码: 验证码
选 项:
虽然发表评论不用注册,但是为了保护您的发言权,建议您注册帐号.