P
P
postya2021-03-12 08:55:31
Vue.js
postya, 2021-03-12 08:55:31

How to validate checkbox group in Element UI?

Application on VUE JS + Element UI
There is a group of checkboxes (checkbox group). It is necessary to check that at least one checkbox is checked
How can this be done?

<el-form
      ref="ruleForm"
      :model="ruleForm"
      :rules="rules">
                
        <el-form-item prop="cars">
            <el-checkbox-group v-model="ruleForm.cars">
                <el-checkbox
                  label="toyota"
                  :checked="ruleForm.carModels.toyota">Toyota
                </el-checkbox>
    
                <el-checkbox
                  label="ferrari"
                  :checked="ruleForm.carModels.ferrari">Ferrari
                </el-checkbox>
    
                <el-checkbox
                  label="suzuki"
                  :checked="ruleForm.carModels.suzuki">Suzuki
                </el-checkbox>
    
                <el-checkbox
                  label="bmw"
                  :checked="ruleForm.carModels.bmw">BMW
                </el-checkbox>
    
            </el-checkbox-group>
        </el-form-item>
        
            <button @click.prevent.stop="validateCars('ruleForm')">Validate Cars</button>
    </el-form>


Data:

ruleForm: {
       cars: [],
       carModels: {
         toyota: true,
         ferrari; false,
         suzuki: false,
         bmw: true
       }
     }    
        
    rules: {
        cars: [
            {
           required: true,
            trigger: 'blur',
             message: 'Choose car',
                   }     
              ]
            }   
     
    methods: {
      async validateCars(formName) {
        try{
          if(await this.refs[formName].validate()) {
            console.log('success')
          }
        }catch(e){}
       }
     }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
T
Tigran Abrahamyan, 2021-03-12
@postya

<span v-if="ruleForm.isValid === false">
  Текст ошибки
</span>

ruleForm: {
  cars: [],
  isValid: null,
  carModels: {
    toyota: true,
    ferrari: false,
    suzuki: false,
    bmw: true
  }
}

validateCars(formName) {
  if (this.ruleForm.cars.length === 0) {
    this.ruleForm.isValid = false;
  } else {
    this.ruleForm.isValid = true;
    console.log('success');
  }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question