0
votes

I'm using vee-validate form validation and I have 3 address fields:

  1. House Number
  2. House Name
  3. Flat Number

All 3 are optional because an address may only have 1, but I need the user to fill in at least one. So I can't make any of them required, and the documentation for cross field validation only handles putting specific validation on a single or multiple fields:

https://logaretm.github.io/vee-validate/advanced/cross-field-validation.html#targeting-other-fields

enter image description here

What is the best way of handling this? I'm no stranger to custom validation rules in my project, I just don't understand the approach here.

Thanks.

<div class="flex flex-wrap pb-2">
  <FormTextInput
    name="addressBuildingNo"
    v-model="value.buildingNo"
    type="text"
    :label="$t('formFields.addressBuildingNo')"
    placeholder="e.g 10"
    :hint="$t('formHints.optional')"
  />

  <FormTextInput
    name="addressFlatNo"
    v-model="value.flatNo"
    type="text"
    :label="$t('formFields.addressFlatNo')"
    :hint="$t('formHints.optional')"
  />

  <FormTextInput
    name="addressBuildingName"
    v-model="value.buildingName"
    type="text"
    :label="$t('formFields.addressBuildingName')"
    :hint="$t('formHints.optional')"
  />
</div>
2

2 Answers

1
votes

Wrap each one in a ValidationProvider and set the required rule on each to be that it's required if neither of the other two are filled out. So the first one would look like this:

<ValidationProvider :rules="{ 'required': (!value.buildingName && !value.flatNo)">
  <FormTextInput
    name="addressBuildingNo"
    v-model="value.buildingNo"
    type="text"
    :label="$t('formFields.addressBuildingNo')"
    placeholder="e.g 10"
    :hint="$t('formHints.optional')"
  />
</ValidationProvider>

If you want more complicated validation, you can also write cross-field validators for each one that check things more specifically (following the docs you pointed out already). See a simplified example here: https://codesandbox.io/s/veevalidate-30-cross-field-optional-3dzxd

0
votes

In the end I just made a hidden field with the value being a combination of all 3 fields.

<FormTextInput name="addressBuilding" type="hidden" v-model="compBuildingValue" rules="required" />

compBuildingValue() {
  return `${this.value.buildingNo.trim()}${this.value.flatNo.trim()}${this.value.buildingName.trim()}`
}