element ui 表单校验(vue)

官方文档

https://element.eleme.cn/#/zh-CN/component/form#dong-tai-zeng-jian-biao-dan-xiang

一丶代码

1,官方内置校验规则

组件

    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()" label-width="140px">
    <el-form-item label="品牌名" prop="name">
      <el-input v-model="dataForm.name" placeholder="品牌名"></el-input>
    </el-form>

script

<script>
  export default {
    data () {
      return {
        dataForm: {
          name: ''
        },
        dataRule: {
          name: [
            { required: true, message: '品牌名不能为空', trigger: 'blur' }
          ]
        }
      }
    }
  }
</script>

2,自定义校验规则

<script>
  export default {
    data () {
      return {
        dataForm: {
          name: ''
        },
        dataRule: {
          name: [
           { validator: (rule, value, callback) => {
             if(value==""){
                callback(new Error('首字母必须填写'));
             }else if( !/^[a-zA-Z]$/.test(value)){
               callback(new Error('首字母只能为英文'));
             }else{
               callback();
             }
            }, trigger: 'blur' }
          ]
        }
      }
    }
  }
</script>

 

posted @ 2021-01-21 22:49  KwFruit  阅读(132)  评论(0编辑  收藏  举报