您当前的位置: 首页 > 

杨林伟

暂无认证

  • 3浏览

    0关注

    3337博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

33avalon - 指令ms-validate(验证绑定)

杨林伟 发布时间:2019-04-16 12:50:58 ,浏览量:3

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()
                }
            }

        }
    })



关注
打赏
1662376985
查看更多评论
立即登录/注册

微信扫码登录

0.1960s