How to implement front-end rules verification in elemnet-ui At least one of the two check boxes must be selected!

In Element UI, you can use form validation rules `rules` to validate form fields. If you want to implement front-end validation to ensure that at least one of the two checkboxes is selected, you can use a custom validation rule. Here's an example of how to use Element UI's `rules` to verify that at least one of two checkboxes is selected:

```vue

<template>
  <el-form :model="formData" :rules="rules" ref="form">
    <el-checkbox-group v-model="selectedOptions">
      <el-checkbox label="Option 1">选项1</el-checkbox>
      <el-checkbox label="Option 2">选项2</el-checkbox>
    </el-checkbox-group>
    <el-button type="primary" @click="submitForm">提交</el-button>
  </el-form>
</template>

<script>
export default {
  data() {
    return {
      formData: {
        selectedOptions: [],
      },
      rules: {
        selectedOptions: [
          { required: true, validator: this.validateSelectedOptions, trigger: 'change' }
        ],
      },
    };
  },
  methods: {
    validateSelectedOptions(rule, value, callback) {
      if (value.length === 0) {
        callback(new Error('至少选择一个选项'));
      } else {
        callback();
      }
    },
    submitForm() {
      this.$refs.form.validate(valid => {
        if (valid) {
          // 表单验证通过,可以执行提交操作
          console.log('表单验证通过');
        }
      });
    },
  },
};
</script>


```

In this example, we create a form with two checkboxes. The validation rules are set through the `rules` attribute, and the `validateSelectedOptions` method is used for custom validation. In the `validateSelectedOptions` method, we check the length of the `selectedOptions` array, if the length is 0, it means that no options are selected, and a validation error is triggered at this time.

When the submit button is clicked, we use the `$refs.form.validate()` method to trigger the validation of the form. If the verification is passed, you can perform the submit operation in the callback function.

Please note that the validation logic in the above example applies to the case where at least one option is selected, and you can make custom modifications as needed to meet specific business needs.

Guess you like

Origin blog.csdn.net/qq_58647634/article/details/132178057