elementUI表单校验——自定义验证

自定义验证

<el-form ref="withdraw" :model="withdraw" :rules="rules">
    <el-form-item label="提现金额:" prop="amount" label-width="200px">
        <el-row :gutter="5">
            <el-col :lg="6" :xs="24">
                <el-input v-model="withdraw.amount">el-input>
            el-col>
            <el-col :lg="2" :xs="24">el-col>
            <el-col :lg="13" :xs="24" style="color: #A9B1BC">
            (提现上限{{account.usableBalance}}元)el-col>
        el-row>
    el-form-item>
el-form>
<el-button type="primary" @click="confirmWithdraw('withdraw')">确 定el-button>
<script>
new Vue({
    el: '#app',
    data: function() {
        /* 自定义表单校验 */
        var validateAmount = (rule, value, callback) => {
            if(value === ''){
                 callback(new Error('请输入提现金额'));
            }else if(value === '0'){
                 callback(new Error('提现金额不能为0'));
            }else if (value > this.account.usableBalance) {
                console.log(value);
              callback(new Error('提现金额不能大于可用余额!'));
            } else {
              callback();
            }
        };
        return {
            account: {
               usableBalance: '2000'
            },
            withdraw: {
              amount: ''
            },
            rules: {
                amount :[
                         { validator: validateAmount, trigger:'blur'}
                         ]
            }
        }
   }
});
script>

关键点

  1. 表单名称 ref=”withdraw”
  2. 表单绑定 :rules=rules
  3. el-form-item prop属性
  4. validateAmount方法
  5. 提交方法:
confirmWithdraw(formName){
        this.$refs[formName].validate((valid) => {
        if (valid) {
           console.log('success submit!!');
        } else {
          console.log('error submit!!');
          return false;
        }
      });
 }

elementUI表单校验——自定义验证_第1张图片

你可能感兴趣的:(vue,elementUI)