avalon2新引入的指令,只能用于form元素上,用于为表单添加验证功能,它需要与ms-duplex, ms-rules指令一起配合使用。
ms-validate的值应该对应一个对象,由于对象比较大,建议写在vm,像下面那样:
vm.validate = {
onValidateAll: function(reasons){
//返回一个数组,如果长度为零说明没有错
},
onError: avalon.noop,//针对单个表单元素(使用了ms-duplex的input, select)
onSuccess: avalon.noop,//针对单个表单元素
onComplete: avalon.noop,//针对单个表单元素
onReset: avalon.noop,//针对单个表单元素
validateInBlur: true, // {Boolean} true,在blur事件中进行验证,触发onSuccess, onError, onComplete回调
validateInKeyup: true, // {Boolean} true,在keyup事件中进行验证,触发onSuccess, onError, onComplete回调
validateAllInSubmit: true, // {Boolean} true,在submit事件中执行onValidateAll回调
resetInFocus: true, // {Boolean} true,在focus事件中执行onReset回调,
deduplicateInValidateAll: false // {Boolean} false,在validateAll回调中对reason数组根据元素节点进行去重
}
在一般情况下validateInBlur, validateInKeyup,validateAllInSubmit,resetInFocus都是默认的就行了。
onError,onSuccess,onComplete, onValidateAll的第一个参数都是reasons对象,this指向被验证的元素,reason里面有你需要的各种东西.
var reason = {
element: elem,
data: field.data,
message: elem.getAttribute("data-" + ruleName + "-message") || elem.getAttribute("data-message") || hook.message,
validateRule: ruleName,
getMessage: getMessage
}
例子:
var vm = avalon.define({
$id: "test",
action: '',
name: '',
add: function(e) {
e.preventDefault()
this.action = "add.php";
this.validate.onManual();
},
update: function(){
this.action = "update.php";
this.validate.onManual();
},
validate: {
validateAllInSubmit: false,
onSuccess: function(reasons, event) {
console.log('成功',reasons)
},
onError: function(reasons, event) {
console.log('有验证没有通过')
},
onValidateAll: function(reasons) {
var form = this
if(reasons.length) {
// 表单有错误
console.log("有验证没有通过",reasons);
return false;
} else {
// 验证成功
form.submit()
}
}
}
})