I have a website login form where users may need to check a specific checkbox before logging in. Here is part of the Vue component code that handles this functionality:
<script setup lang="ts">
import {ref, defineProps} from 'vue';
import useVuelidate from '@vuelidate/core';
import {required, sameAs, email as emailValidation, requiredIf, helpers} from '@vuelidate/validators';
interface Props {
showAcceptTermsBox: boolean;
}
const props = defineProps<Props>();
const email = ref('');
const acceptTerms = ref(false);
const rules = computed(() => ({
email: {
required: helpers.withMessage('Please fill out e-mail', required),
email: helpers.withMessage('Please fill out e-mail correctly', emailValidation)
},
acceptTerms: {
required: helpers.withMessage('Please accept terms and conditions', requiredIf(() => props.showAcceptTermsBox)),
sameAs: helpers.withMessage('Please accept terms and conditions', sameAs(true))
}
}));
const v$ = useVuelidate(rules, {
email,
acceptTerms
}, {
$scope: false
});
</script>
<template>
<form>
<label for="email">E-mail:</label>
<input type="email" v-model="email" id="email" />
<div v-if="showAcceptTermsBox">
<input type="checkbox" v-model="acceptTerms" id="acceptterms" />
<label for="acceptterms">Accept</label>
</div>
<button type="submit">Submit</button>
</form>
</template>
The Checkbox will only appear if the showAcceptTermsBox
property is set to true. I want the validation to apply only when the checkbox is visible but currently, it gets validated whether the property is true or false. Is there a way to conditionally validate the checkbox using something similar to requiredif with sameAs?
Note that the validation works fine for other fields like the email input. Any guidance on resolving this issue would be greatly appreciated.
Thank you!