※当サイトの記事には、広告・プロモーションが含まれます。

VeeValidateを使ってみる

nazology.net

このように、世界最初のエアコンは、人が涼むためではなく、印刷工場の湿気を取り除くために作られたのです。

エアコン作った天才って誰なの? 当初の目的は人間のためじゃなかった!? - ナゾロジー

⇧ amazing...

VeeValidateとは?

Vue 2.x と Vue 3.x でそれぞれバージョンが異なるっぽいけども、

■Vue 2.x用

vee-validate.logaretm.com

Template Based Form Validation Framework for Vue.js

https://vee-validate.logaretm.com/v3/

■Vue 3.x用

vee-validate.logaretm.com

Form Validation for Vue.js

https://vee-validate.logaretm.com/v4/

⇧ Vue.jsのためのForm Validationということらしい。

GitHubのドキュメントに、

github.com

Form Validation for Vue.js

https://github.com/logaretm/vee-validate

Vue version support

The main v4 version supports Vue 3.x only, for previous versions of Vue, check the following the table

vue Version vee-validate version Documentation Link
2.x 2.x or 3.x v2 or v3
3.x 4.x v4

https://github.com/logaretm/vee-validate

⇧ バージョンの記載ありましたね。

Vue CLIでVue.jsのプロジェクト作成

何はともあれ、Node.jsがインストールされているのを確認し、適当なディレクトリを作成しておいて、移動したらば、Vue CLIをインストール。

そしたらば、Vue CLIでVue.jsのプロジェクト作成で。

今回はすべてのオプションを選択してみました。

Vueのバージョンは、2.xです。

class-style componentの利用は、Yesで。

Babelの利用も、Yesで。

Vue Routerのhistory modeの利用も、Yesで。

Sass/SCSS(with dart-sass)を選択。

ESLint + Prettier を選択。

Lint on save を選択。

Jest を選択しました。

Cypressを選択しました。

In dedicated config files を選択しました。

ここまでの選択を保存するかについては、Noを選択しました。

プロジェクト作成が開始されます。

Vue.jsのプロジェクトのフォルダをVisual Studio Codeで開いて、

.eslintrc.jsに、prettierの設定を追加しとかないとエラーが出るので、追加しときます。

■C:\Users\Toshinobu\Desktop\soft_work\vue_work\vue-vee-validate\hello-world\.eslintrc.js

module.exports = {
  root: true,
  env: {
    node: true,
  },
  extends: [
    "plugin:vue/essential",
    "eslint:recommended",
    "@vue/typescript/recommended",
    "plugin:prettier/recommended",
  ],
  parserOptions: {
    ecmaVersion: 2020,
  },
  rules: {
    "no-console": process.env.NODE_ENV === "production" ? "warn" : "off",
    "no-debugger": process.env.NODE_ENV === "production" ? "warn" : "off",
    "prettier/prettier": [
      "error",
      {
        endOfLine: "auto",
      },
    ],
  },
  overrides: [
    {
      files: [
        "**/__tests__/*.{j,t}s?(x)",
        "**/tests/unit/**/*.spec.{j,t}s?(x)",
      ],
      env: {
        jest: true,
      },
    },
  ],
};
    

VeeValidateを使ってみる

Vue.jsのプロジェクトが作成できたので、本題のVeeValidateを使ってみる。

vee-validate.logaretm.com

⇧ 上記を参考に、vee-validateをインストール。Vue 2.xは、vee-validateの3.xを選択する感じになるらしい。

cd [Vue.jsのプロジェクトのディレクトリ]
npm install vee-validate@3 --save

で、ドキュメントのBasic Exampleが何故か、中途半端なとこまでしか記載してくれてないという...適当過ぎるでしょ...

というわけで、VeeValidateが動くとこまで実装。

■C:\Users\Toshinobu\Desktop\soft_work\vue_work\vue-vee-validate\hello-world\src\main.ts

import Vue from "vue";
import App from "./App.vue";
import "./registerServiceWorker";
import router from "./router";
import store from "./store";
import { ValidationProvider, extend } from "vee-validate";

Vue.config.productionTip = false;
// Add a rule.
extend("secret", {
  validate: (value) => value === "example",
  message: "This is not the magic word",
});

// Register it globally
Vue.component("ValidationProvider", ValidationProvider);

new Vue({
  router,
  store,
  render: (h) => h(App),
}).$mount("#app");

■C:\Users\Toshinobu\Desktop\soft_work\vue_work\vue-vee-validate\hello-world\src\views\user\index.vue

<template>
  <div>
    <ValidationProvider rules="secret" v-slot="{ errors }">
      <input v-model="email" type="text" />
      <span>{{ errors[0] }}</span>
    </ValidationProvider>
  </div>
</template>

<script lang="ts">
import { Component, Vue } from "vue-property-decorator";
@Component({
  components: {},
})
export default class User extends Vue {
  private email = "";
}
</script>    

■C:\Users\Toshinobu\Desktop\soft_work\vue_work\vue-vee-validate\hello-world\src\router\index.ts

import Vue from "vue";
import VueRouter, { RouteConfig } from "vue-router";
import HomeView from "../views/HomeView.vue";

Vue.use(VueRouter);

const routes: Array<RouteConfig> = [
  {
    path: "/",
    name: "home",
    component: HomeView,
  },
  {
    path: "/about",
    name: "about",
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: () =>
      import(/* webpackChunkName: "about" */ "../views/AboutView.vue"),
  },
  {
    path: "/user",
    name: "user",
    component: () =>
      import(/* webpackChunkName: "about" */ "../views/user/index.vue"),
  },
];

const router = new VueRouter({
  mode: "history",
  base: process.env.BASE_URL,
  routes,
});

export default router;

■C:\Users\Toshinobu\Desktop\soft_work\vue_work\vue-vee-validate\hello-world\src\App.vue

import Vue from "vue";
import VueRouter, { RouteConfig } from "vue-router";
<template>
  <div id="app">
    <nav>
      <router-link to="/">Home</router-link> |
      <router-link to="/about">About</router-link> |
      <router-link to="/user">USER</router-link>
    </nav>
    <router-view />
  </div>
</template>

<style lang="scss">
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
}

nav {
  padding: 30px;

  a {
    font-weight: bold;
    color: #2c3e50;

    &.router-link-exact-active {
      color: #42b983;
    }
  }
}
</style>

で、保存して、

で、ブラウザからアクセスして、USERのリンクをクリック。

example まで入力しないと、バリデーションでメッセージが出るようです。

とりあえず、VeeValidateが動くのは確認できたので、スタート地点に立った感じでしょうかね...

それにしても、ドキュメントがドイヒーですね...

毎度モヤモヤ感が半端ない...

今回はこのへんで。