LoginSignup
1
3

More than 3 years have passed since last update.

vee-validate で「特定のフィールドに固有のバリデーションメッセージを設定する

Last updated at Posted at 2019-08-29

はじめに

「特定のフィールドの regex バリデーションメッセージを変更したい」という要件が上がってきたんだけど、vee-validateではどう実現するのが正解がわからなかった。

やりたいこと

  • regex のグローバルで設定しているバリデーションメッセージは変更したくない。
  • 特定のフィールドの regex のバリデーションメッセージだけを変更したい。
  • 他の検証ルールのメッセージはそのまま。

やったこと

lib/validatormessage.ts
import { Validator } from 'vee-validate';

export function getError(
    validator: Validator,
    field: string,
    ruleMsssageMap: { [rule: string]: string }
): string | null {
    const errors = validator.errors.items.filter((e) => e.field === field);
    if (errors.length > 0) {
        const error = errors[0];
        let isExists = false;
        for (const rule in ruleMsssageMap) {
            if (error.rule === rule) {
                isExists = true;
            }
        }

        if (isExists) {
            return ruleMsssageMap[error.rule];
        } else {
            return validator.errors.first(field);
        }
    }

    return null;
}
xxx.vue
<template>
  <input
    type="text"
    name="myfield"
    v-model="myfieldValue"
    v-validate="{ required: true, regex: /[1-9]/ }"
  />
  <div v-show="myfieldError">
    {{ myfieldError  }}
  </div>
</template>
<script lang="ts">
import { getError } from '@lib/validatormessage'
...
computed: {
    myfieldError: {
      get: (): string | null => {
        return getError(this.$validator, 'myfield' { regex: 'custom error message.' })
      },
    },
  },
<script>

まとめ

特定のフィールドで、他の検証ルールに影響をあたえず、特定の検証ルールにのみバリデーションメッセージを設定することに成功しました。
みんなはどのように実装しているんだろう…(゜_゜)

1
3
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
3