EasyValidation3.0是badqiu和Ivan Li在前人基础上开发的基于prototype的前台验证系统(应该算系统了),官方网站
http://wiki.javascud.org/display/si/Javascript_EasyValidation (强人,帮忙宣传一下),并由jianfeng008cn进行了部分的重写
http://jianfeng008cn.iteye.com/blog/38717 。通过读这些代码,真是学到了不少东西,赞!!
摘出几段代码来增强记忆
引用
Validator.messagesSource = Validator.messagesSourceCn;
Validator.messages = {};
//init Validator.messages
Validator.messagesSource.each(function(ms){
Validator.messages[ms[0]] = ms[1];
//把数组validator.messageSource 中的数据导入到对象validator.messages中,格式为Validator.messages.validate-qq = '请输入有效的qq号码'
});
Validator.prototype = {
initialize : function(className, test, options) {
this.options = Object.extend({
ignoreEmptyValue : true,
depends : []
}, options || {});
//相当于this.options = {ignoreEmptyValue:ture,....}好处是可以在初始化时设置两个参数的值;
this._test = test ? test : function(v,elm){ return true };
this._error = Validator.messages[className] ? Validator.messages[className] : Validator.messages['validation-failed'];
this.className = className;
this._dependsTest = this._dependsTest.bind(this);
this._getDependError = this._getDependError.bind(this);
},
_dependsTest : function(v,elm) {
if(this.options.depends && this.options.depends.length > 0) {
var dependsResult = $A(this.options.depends).all(function(depend){
return Validation.get(depend).test(v,elm);
});
return dependsResult;
}
return true;
},
test : function(v, elm) {
if(!this._dependsTest(v,elm))
return false;
if(!elm) elm = {}
return (this.options.ignoreEmptyValue && ((v == null) || (v.length == 0))) || this._test(v,elm,Validation.Utils.getArgumentsByClassName(this.className,elm.className),this);
},
_getDependError : function(v,elm,useTitle) {
var dependError = null;
$A(this.options.depends).any(function(depend){
var validation = Validation.get(depend);
if(!validation.test(v,elm)) {
dependError = validation.error(v,elm,useTitle)
return true;
}
return false;
});
return dependError;
},
error : function(v,elm,useTitle) {
var dependError = this._getDependError(v,elm,useTitle);
if(dependError != null) return dependError;
var args = Validation.Utils.getArgumentsByClassName(this.className,elm.className);
var error = this._error;
if(typeof error == 'string') {
if(v) args.push(v.length);
error = Validation.Utils.format(this._error,args);
}else if(typeof error == 'function') {
error = error(v,elm,args,this);
}else {
alert('error must type of string or function');
}
if(!useTitle) useTitle = elm.className.indexOf('useTitle') >= 0;
return useTitle ? ((elm && elm.title) ? elm.title : error) : error;
}
}