avalon2表单验证,非必填字段在不填写的时候不能通过验证
代码
var vm = avalon.define({
$id: "validate1",
aaa : "",
validate: {
onError: function(reasons) {
reasons.forEach(function(reason) {
console.log(reason.getMessage())
})
},
onValidateAll: function(reasons) {
if(reasons.length) {
alert(reasons[0].getMessage())
} else {
alert('全部通过')
}
}
}
})
截图
查看源码 avalon/src/directives/duplex/addValidateField.js 中 validate 方法中
var next = function (a) {
if (field.norequired && value === '') {
a = true
}
......
}
有判断 field.norequired 是否为非必填字段 ,但貌似 norequired 属性从未赋值过
我的解决办法
在源码 avalon/src/directives/duplex/addValidateField.js 改造
代码如下
module.exports = function addField(node, vnode) {
var field = node.__ms_duplex__
var rules = vnode['ms-rules']
if (rules && !field.validator) {
while (node && node.nodeType === 1) {
var validator = node._ms_validator_
if (validator) {
if (rules['required'] === undefined || rules['required'] === false)
field.norequired = true;
field.rules = rules
field.validator = validator
if (avalon.Array.ensure(validator.fields, field)) {
validator.addField(field)
}
break
}
node = node.parentNode
}
}
}
新增了 这么一段 给 norequired 属性赋值 解决了非必填验证的问题
if (rules['required'] === undefined || rules['required'] === false)
field.norequired = true;
但不知道此方法是否是合理?