Sihem Hcine
Sihem Hcine

Reputation: 1129

Cannot validate el-select elementUI

I'm trying to create custom validation with el-select such way :

In my template :

 <el-form ref="form" >
<el-form-item   prop="fieldProp" >
    <el-select class="dialog-select" v-model="informationForm.age"  @change="validateDropdown" 
    placeholder="age" style="width: 100%"  >
      <el-option label="11" value="1"></el-option>
      <el-option label="22" value="2"></el-option>
    </el-select>
  </el-form-item>
</el-form>

In data :

   data() {
        let  checkCurrency = (rule, value, callback) => {
            if (!value) {
                return callback(new Error('Please input the age'));
            }
        };
        return {
                fieldProp: [
                    { validator: checkCurrency, trigger: 'change' }
                ]
              }
         } 

In my methods:

validateDropdown() {
            this.$refs.form.validateField('fieldProp')
        }

And calling the validation method : in submit

   submit() {
            this.validateDropdown(); 
        }

But nothing happens. Any idea please ?

Upvotes: 1

Views: 4261

Answers (1)

BTL
BTL

Reputation: 4666

I encourage you to read the element ui doc about (custom) form validation : https://element.eleme.io/#/en-US/component/form#custom-validation-rules

In your case you should add a model and rules prop to your form and then use the proper validate method.

Example code :

<el-form ref="form" :model="informationForm" :rules="rules">
  <el-form-item prop="age" >
    <el-select class="dialog-select" v-model="informationForm.age" placeholder="age" style="width: 100%">
      <el-option label="11" value="1"></el-option>
      <el-option label="22" value="2"></el-option>
    </el-select>
  </el-form-item>
</el-form>
   data() {
        let  checkCurrency = (rule, value, callback) => {
            if (!value) {
                return callback(new Error('Please input the age'));
            }
        };
        return {
          rules: {
            fieldProp: [
              { required: true, validator: checkCurrency, trigger: 'change' }
            ]
          }
        }
   }

No need for validateDropdown because your field is already validate on each change thanks to this : trigger: 'change'.

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

Upvotes: 1

Related Questions