Element UI表单验证

Element UI表单验证

  •  2019 年 6 月 25 日
  •  1382
  •  Vue ElementUI 

Element UI的Form组件提供了表单验证的功能,只需要通过rules属性传入约定的验证规则,并将form-item的prop属性设置为需校验的字段名即可。官网文档见https://element.eleme.cn/#/zh-CN/component/form。校验规则参见async-validator。下面我们看一个简单的例子:

表单

<el-form :model="user" :rules="rules" ref="userForm">
    <el-form-item prop="name" label="名称">
        <el-input v-model="user.name"></el-input>
    </el-form-item>
</el-form>

校验规则

data() {
    return {
        rules: {
            name: [
                {required: true, type: 'string', message: '请输入名称', trigger: 'blur'}
            ]
        }
    }
}

  • rules是form表单中:rules指向的名称
  • rules中的name是表单中prop指向的名称

自定义校验规则

data() {
    var validateName = (rule, value, callback) => {
        if (!value) {
            callback(new Error('请输入名称'));
        } else {
            // do something
            callback();
        }
    };
    return {
        rules: {
            name: [
                {validator: validateName, required: true, trigger: 'blur'}
            ]
        }
    }
}

验证

this.$refs.userForm.validate(valid => {
    if (valid) {
        // submit
    }
});

校验规则中的type

  • string: Must be of type string. This is the default type.
  • number: Must be of type number.
  • boolean: Must be of type boolean.
  • method: Must be of type function.
  • regexp: Must be an instance of RegExp or a string that does not generate an exception when creating a new RegExp.
  • integer: Must be of type number and an integer.
  • float: Must be of type number and a floating point number.
  • array: Must be an array as determined by Array.isArray.
  • object: Must be of type object and not Array.isArray.
  • enum: Value must exist in the enum.
  • date: Value must be valid as determined by Date
  • url: Must be of type url.
  • hex: Must be of type hex.
  • email: Must be of type email.

扫一扫分享到微信

已有 条评论
写评论