6
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

VeeValidate3で別フィールドの値をvalidation時に参照する

Posted at

概要

Vue.jsで入力項目のvalidationを行う際、VeeValidateのライブラリを使うケースが多いと思います。今回はそのVeeValidate3系のバージョンで、パスワードの再入力時の同一チェックのように、別フィールドを参照してvalidationしたい場合の実装方法について書いてみます。

前提など

実装サンプル

  • pluginに設定しているvee-validate.jsの内容は以下です。今回はパスワードの再入力欄のほうにカスタムのvalidationを設定しています。必要箇所のみ抜粋して記載しています。
vee-validate.js
extend("passwordReInput", {
  params: ["target"],
  validate(value, { target }) {
    return value === target;
  },
  message: "上のパスワード欄と同様のものを入力して下さい"
});
  • component側での実装例は以下です。rulesで参照するフィールドのValidationProviderのnameに頭に「@」を付与して、別フィールドを参照しています。なお、以下のサンプルはtemplate部分のみとし、エラーメッセージの表示部分についてのロジックは記載を割愛してます。(errorsを別componentに渡して表示しています)
PasswordSample.vue
<template>
  <div>
    <validation-observer v-slot="{ invalid }">
      <div class="form-group">
        <label for="password">パスワード</label>
        <validation-provider v-slot="{ errors }" rules="required|min:6" name="password">
          <input type="password" class="form-control" v-model="password" />
          <ErrorMessageComponent :errors="errors" />
        </validation-provider>
      </div>
      <div class="form-group">
        <label for="passwordReInput">パスワード再入力</label>
        <validation-provider v-slot="{ errors }" rules="passwordReInput:@password" name="passwordReInput">
          <input type="password" class="form-control" v-model="passwordReInput" />
          <ErrorMessageComponent :errors="errors" />
        </validation-provider>
      </div>
    </validation-observer>
  </div>
</template>

  • 表示はこんな風になるイメージです。(エラーメッセージ部分の表示はbootstrapを使用)
スクリーンショット 2020-07-21 5.01.31.png
6
2
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
6
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?