如何使用 vee-validate 创建交叉验证字段?

How to create cross validation field with vee-validate?

我正在尝试使用 vee-validate 根据其他字段 (select) 的 selection 来验证 3 个字段(文本字段),但我似乎无法理解我该怎么做。

基本上,我有一个包含 5 个值的 select 框,如果 selected 值等于 1 或 2,则需要表单中的其他 3 个字段。

这是一个例子

如果我select"Ausente"(值1)或"A desenvolver"(值2),其他3个字段都是必填项。

这是我想出的代码

<v-col cols="2">
    <validation-provider
        rules="required"
        v-slot="{ errors }"
        name="skillLevel"
    >  <!-- If this select has value of 1 or 2 -->
        <v-select
            v-model="answers[n-1][index].skillLevel"
            outlined
            :error-messages="errors"
            :items="selectLevels"
            label="Selecione"
            item-text="level"
            item-value="value"
        ></v-select>
    </validation-provider>
</v-col>

<!-- These 3 fields must be required -->
<v-col cols="2">
    <validation-provider
        name="feedback"
        rules="required||isRequiredWith:@skillLevel"
    >
        <v-textarea v-model="answers[n-1][index].feedBack" outlined rows="3"></v-textarea>
    </validation-provider>
</v-col>

<v-col cols="2">
    <validation-provider name="selfAppraisal" rules="required">
        <v-textarea
            v-model="answers[n-1][index].selfAppraisal"
            outlined
            rows="3"
        ></v-textarea>
    </validation-provider>
</v-col>

<v-col cols="3">
    <validation-provider name="feedforward" rules="required">
        <v-textarea v-model="answers[n-1][index].feedForward" outlined rows="3"></v-textarea>
    </validation-provider>
</v-col>

这是我的 js

import { required} from "vee-validate/dist/rules";
import {
  extend,
  ValidationObserver,
  ValidationProvider,
  setInteractionMode
} from "vee-validate";

setInteractionMode("eager");

extend("required", {
  ...required,
  message: "Campo não pode ficar em branco"
});

extend("isRequiredWith", {
  params: ["target"],
  validate(value, { target }) {
    if (target === 1 || target === 2) {
      console.log(target);
      //Problem is here, i'm messing up the value/target, don't what i need to check
      console.log("cannot be empty");
    }
  },
  message: "Required"
});

我不确定出了什么问题,看来您的代码基本上应该可以工作。不过我试了一下,当目标值改变时,它从不费心去 运行 和 isRequiredWith 验证。所以这里有一个不需要制定你自己的规则的替代方法:

<validation-provider
    name="feedback"
    :rules="{required:(answers[n-1][index].skillLevel == 1 || answers[n-1][index].skillLevel == 2)}"
>
    <v-textarea v-model="answers[n-1][index].feedBack" outlined rows="3"></v-textarea>
</validation-provider>

虽然不漂亮,但很管用。请参阅此处的简化示例:https://codesandbox.io/s/veevalidate-30-cross-field-validation-gpkj9