LoginSignup
1
1

More than 1 year has passed since last update.

vee-validate2のクロスフィールドのカスタムルール設定(例:開始日、終了日チェック)

Last updated at Posted at 2022-04-01

対象

vee-validateのカスタムルールで別のフィールドの値と比較した
クロスフィールドのチェックをしたいのに
検索するとvee-validate v3系の記事ばかりでした。
現場ではv2系(2.2.15)を使っているため、そのままではうまくいかなかったので
v2系のクロスフィールドのカスタムルールの設定の仕方を紹介したいと思います。
公式のクロスフィールドに関する記事も、対象の値の取得の仕方までの記述がなく
参考にならず…。

環境

vue v2
vee-validate v2

概要

To(終了日)に、From(開始日)以降の日付が設定されているかチェックするサンプルです。

サンプル

  • 追加しているカスタムルールは、afterDateです。
    options: { hasTarget: true }paramNames: ["targetValue"]を設定することで
    対象となるFrom(開始日)の値を取得できます。
index.js
import Vue from "vue";
import VeeValidate, { Validator } from "vee-validate";
import ja from "vee-validate/dist/locale/ja";

Validator.localize('ja', ja);
Vue.use(VeeValidate, { local: ja });
Vue.component("ValidationProvider", VeeValidate.ValidationProvider);
Vue.component("ValidationObserer", VeeValidate.ValidationObserer);

Validator.extend('afterDate', {
  options: { hasTarget: true },
  paramNames: ["targetValue"],
  getMessage(field, targetName) {
    return `${field}は、${targetName}よりも後の日付を入力してください`;
  },
  validate(value, target) {
    const afterDate = value;
    const beforeDate = target.targetValue;
    if (!afterDate || !beforeDate) return true;
    // yyyyMMdd形式でデータ来る想定で単純比較してますが、
    // 適宜、日付比較関数を使ってください。
    return beforeDate <= afterDate;
  }
});
  • vue側では、vidの設定が必要です。
    (*vee-validate v3系だと@のみでOKみたいですが)
index.vue
<template>
  <div>
    <validation-provider v-slot="{ errors }" name="開始日" vid="from" rules="required">
      <input type="date" v-model="dayFrom" />
      <p v-if="errors.length">{{ errors[0] }}</p>
    </validation-provider>
    <label></label>
    <validation-provider v-slot="{ errors }" name="終了日" vid="to" rules="required|afterDate:from">
      <input type="date" v-model="dayTo" />
      <p v-if="errors.length">{{ errors[0] }}</p>
    </validation-provider>
  </div>
</template>
<!-- 省略 -->

最後に

  • 単純に日付を比較するならdate_formatとafter(もしくはbefore)でいいのでは? とも思い
    試したのですがdate_formatがうまく機能しませんでした。
    そのためカスタムルールで自作することに。
    v2系か、v3系で大きく記述が異なるのでかなり苦労しましたが、
    この記事がお役に立てればなによりです。
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1