[Vuejs]-Vuelidate: Only validate checkbox if property is true

1πŸ‘

βœ…

It just needs one trick, here you go.

import {
  computed,
} from 'vue';

const rules = computed(() => {
  let dynamicRules: any = {
    email: {
      required: helpers.withMessage(
        'Please fill out e-mail',
        required,
      ),
      email: helpers.withMessage(
        'Please fill out e-mail correctly',
        emailValidation,
      ),
    },
  }
  // Dynamically add check fields βœ…
  if(props.showAcceptTermsBox) {
    dynamicRules = {
      ...dynamicRules,
      acceptTerms: {
        required: helpers.withMessage(
          'Please accept terms and conditions',
          requiredIf(() => props.showAcceptTermsBox),
        ),
        sameAs: helpers.withMessage(
          'Please accept terms and conditions',
          sameAs(true),
        ),
      }
    }
  }
  return dynamicRules;
});

πŸ‘€xgqfrms

2πŸ‘

As an option, you can use a custom validator that always returns true in case showAcceptTermsBox is set to false. Something like so:

acceptTerms: {
  checked: helpers.withMessage(
    "Please accept terms and conditions",
    (value: boolean) => (showAcceptTermsBox ? value : true)
  ),
},

Check out this example for more details (you can toggle showAcceptTermsBox in the component’s props section).

πŸ‘€oozywaters

Leave a comment