Home > front end >  How to make a cross field validation with a custom message in vee-validate?
How to make a cross field validation with a custom message in vee-validate?

Time:10-21

See enter image description here

CodePudding user response:

Updated answers

Those pages helped me out:

This is how you can achieve this by referencing the various inputs.

<template>
  <ValidationObserver>
    <ValidationProvider
      :rules="{ required: true, between: { min: '@min', max: '@max' } }"
      v-slot="{ errors }"
    >
      <ValidationProvider
        rules="required"
        vid="min"
        v-slot="{ errors, message }"
      >
        <input type="number" v-model.number="minValue" />
        <span>{{ errors[0] }}</span>
        <div>message here: {{ message }}</div>
      </ValidationProvider>

      <input type="number" v-model.number="value" />
      <span>{{ errors[0] }}</span>

      <ValidationProvider vid="max" rules="required" v-slot="{ errors }">
        <input type="number" v-model.number="maxValue" />
        <span>{{ errors[0] }}</span>
      </ValidationProvider>
    </ValidationProvider>
  </ValidationObserver>
</template>

<script>
import { extend } from "vee-validate";

extend("between", {
  params: ["min", "max"],
  validate(value, { min, max }) {
    return value >= min && value <= max;
  },
  message: (_, values) =>
    `This field value must be between ${values["_min_"]} and ${values["_max_"]}`,
});

export default {
  data: () => ({
    minValue: 0,
    value: 1,
    maxValue: 10,
  }),
};
</script>

Here is a working codesandbox.


Not sure why referencing another field is not working so far: https://vee-validate.logaretm.com/v3/advanced/cross-field-validation.html#targeting-other-fields

You can achieve it simply by changing rules="required|between:@min,@max" into rules="required|between:4,25".

Let me see if I can find the way of writing it by referencing another field!

  • Related