0

I have an Ant Design form with model validation function. It has three checkboxes:

<a-form-model-item has-feedback label="CI/CD Stages" prop="stage">
   <a-checkbox-group v-model="form.stage">
     <a-checkbox value="1" name="stage"> Build Stage 1</a-checkbox>
     <a-checkbox value="2" name="stage"> Build Stage 2</a-checkbox>
     <a-checkbox value="3" name="stage"> Build Stage 3 </a-checkbox>
   </a-checkbox-group>
</a-form-model-item>

I want the validation to fail when Build Stage 2 and Build Stage 3 are selected.

data() {
  ...
  let checkModuleStage = (rule, value, callback) => {
      clearTimeout(checkPending);
      checkPending = setTimeout(() => {
        if (value === [2, 3] || value === [3, 2]) {
          callback(
            new Error(
              "You have selected both Stage 2 and Stage 3. Only one can be selected:"
            )
          );
        } else {
          callback();
        }
      }, 1000);
}
return {
  rules: {
    stage: [
          {
            type: 'array',
            required: true,
            message: 'Please select at least one stage',
            trigger: 'change',
          },
          { validator: checkModuleStage, trigger: "change" },
        ],
  }
}

But now both 2 and 3 can still be selected altogether and whenever I try to submit the form it just shows the check passed. Does anyone know how to solve this? Thanks!

demid
  • 348
  • 5
  • 16
  • If you check both Stages 2 and 3, what is the actual value of the `value` parameter when `checkModuleStage` is invoked? Is it a permutation of `["2", "3"]` (with string values)? – jarmod Aug 18 '21 at 13:23
  • Yes turns out it should be two strings like `["2", "3"]`. The answer below solved it. – demid Aug 19 '21 at 01:03

1 Answers1

2

you have to change your if statement under checkModuleStage to:

if (value.some((x) => x === "2") && value.some((x) => x === "3"))

You're "if" statement doesn't work because:

  1. the values are stored as strings and your looking for numbers
  2. to compare two Array that's not the right way, you have to loop through every array and compare every value (check this link)
Daly
  • 265
  • 2
  • 11