Last active
December 14, 2015 11:39
-
-
Save kampfer/5081135 to your computer and use it in GitHub Desktop.
form&field
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
functon Form() {} | |
Form.prototype = { | |
addField : function(name, field) {}, | |
getField : function(name) {}, | |
getFieldAt : function(index) {}, | |
removeField : function(name) {}, | |
removeFieldAt : function(index) {}, | |
validate : function(success, error) {}, | |
//TODO | |
//1.自定义的回调 | |
//2.两种提交方式:ajax和普通模式 | |
submit : function(method) {}, | |
disable : function() {}, | |
enable : function() {}, | |
serialize : function() {}, | |
dispose : function() {} | |
}; | |
function Field(type, name, value) {} | |
Field.prototype = { | |
//TODO 1.支持异步的验证函数 | |
addRule : function(name, handle, msg) {}, | |
/** | |
* how to use: | |
* | |
* field.validate(['empty', 'maxLength'], function() { | |
* console.log('success'); | |
* }, function() { | |
* console.log('error'); | |
* }); | |
* | |
* field.validate(function() { | |
* console.log('success'); | |
* }, function() { | |
* console.log('error'); | |
* }); | |
* | |
* field.validate(function() { | |
* console.log('success'); | |
* }); | |
* | |
**/ | |
validate : funciton(rules, success, error) { | |
if(typeof rules === 'function') { | |
rules = this._rules; | |
success = rules; | |
} else if(rules.length) { | |
rules = this.getRules(rules); | |
} | |
var ret = true, | |
that = this, | |
callback = function(index) { | |
return function(ret) { | |
ret = !!ret; | |
if(ret) { | |
if(index === that._rules.length && success) { | |
success(); | |
} | |
this.getRuleAt(index + 1).handle( callback(index + 1) ); | |
} else { | |
if(error) { | |
error(); | |
} | |
this.setError( this.getRuleAt(index + 1).msg ); | |
} | |
} | |
}; | |
this.getRuleAt(0).handle( callback(0) ); | |
}, | |
setTip : function() {}, | |
setHint : function() {}, | |
setError : function() {}, | |
setSuccess : function() {}, | |
hide : function() {}, | |
show : function() {}, | |
disable : function() {}, | |
enable : function() {}, | |
dispose : function() {} | |
} |
如何使用:
var field = new Field();
userName = new UserName(field);
function UserName(field) {
field.addRule(1);
field.addRule(2);
this.validate = function() {
return field.validate();
};
this.restore = function() {
field.removeRule();
return field;
};
}
UserName.prototype = new Field();
field的验证规则可以在运行时被删除、重置、禁用和激活,还可以添加新规则
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
抽象的表单和字段组件. 处理字段验证和表单提交逻辑.
字段组件的逻辑相对固定,所以计划封装一些常用验证逻辑.
表单组件提交后的处理操作变化相对频繁, 所以只预留一些最简单的处理.