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

VeeValidateをElement UI で使ってみる

scienceportal.jst.go.jp

 新型コロナウイルスのさまざまな変異株に対する抗体の量を1滴の血液から8分で測定できるシステムを開発した、と理化学研究所理研)などの研究グループが発表した。

どんな新型コロナ変異株の抗体量も血液1滴で判定 理研、8分で分かる自動測定システムを開発 | Science Portal - 科学技術の最新情報サイト「サイエンスポータル」

⇧ 検査費用とか気になりますな...

VeeValidateをElement UI で使ってみる

VeeValidateのドキュメントを見ると、

vee-validate.logaretm.com

⇧ Element UIと一緒に使えるということで試してみます。

Element UIのインストール方法は、

element.eleme.io

⇧ 上記のドキュメントで確認できます。

Vue.jsのプロジェクトは、

ts0818.hatenablog.com

⇧ 上記の記事で作成したものを利用していきます。

ということで、Element UIをインストールします。

インストールが済むと、package.jsonのdependenciesに追加されてるのが確認できます。

そしたらば、修正した部分のソースコード

■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 { ValidationObserver, ValidationProvider } from "vee-validate";
import ElementUI from "element-ui";
import "element-ui/lib/theme-chalk/index.css";
import { extend } from "vee-validate";
import * as rules from "vee-validate/dist/rules";

Object.keys(rules).forEach((rule) => {
  extend(rule, rules[rule as keyof typeof rules]);
});

// with typescript
for (const [rule, validation] of Object.entries(rules)) {
  extend(rule, {
    ...validation,
  });
}

Vue.config.productionTip = false;
Vue.use(ElementUI);

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

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>
    <ValidationObserver ref="observer" v-slot="{ handleSubmit }">
      <el-form ref="form" label-width="120px">
        <ValidationProvider
          rules="required|email"
          name="Email"
          v-slot="{ errors }"
        >
          <el-form-item :error="errors[0]" label="Email">
            <el-input v-model="email" />
          </el-form-item>
        </ValidationProvider>

        <ValidationProvider
          rules="required"
          name="Password"
          vid="password"
          v-slot="{ errors }"
        >
          <el-form-item prop="pass" :error="errors[0]" label="Password">
            <el-input type="password" v-model="password" />
          </el-form-item>
        </ValidationProvider>

        <ValidationProvider rules="required" name="Subject" v-slot="{ errors }">
          <el-form-item :error="errors[0]" label="Subject">
            <el-select v-model="subject" placeholder="Select Subject">
              <el-option label="None" value></el-option>
              <el-option label="Subject 1" value="s1"></el-option>
              <el-option label="Subject 2" value="s2"></el-option>
            </el-select>
          </el-form-item>
        </ValidationProvider>

        <ValidationProvider
          rules="required|length:2"
          name="Drinks"
          v-slot="{ errors }"
        >
          <el-form-item :error="errors[0]" label="Drinks">
            <el-checkbox-group v-model="choices">
              <el-checkbox label="Coffee"></el-checkbox>
              <el-checkbox label="Tea"></el-checkbox>
              <el-checkbox label="Soda"></el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </ValidationProvider>
        <el-form-item>
          <el-button type="primary" @click="handleSubmit(onSubmit)"
            >Create</el-button
          >
          <el-button @click="resetForm">Reset</el-button>
        </el-form-item>
      </el-form>
    </ValidationObserver>
  </div>
</template>

<script lang="ts">
/* eslint-disable no-console */
import { Component, Vue } from "vue-property-decorator";
@Component({
  components: {},
})
export default class User extends Vue {
  private email = "";
  private password = "";
  private confirmation = "";
  private subject = "";
  private choices = [];

  private onSubmit() {
    const isValid = (this.$refs.observer as any).validate();
    console.log(isValid);
  }

  private resetForm() {
    this.email = "";
    this.password = "";
    this.confirmation = "";
    this.subject = "";
    this.choices = [];
    this.$nextTick(() => {
      (this.$refs.observer as any).reset();
    });
  }
}
</script>

<style lang="scss" scoped>
::v-deep {
  .el-form-item__content {
    text-align: left !important;
  }
}
</style>

⇧ で保存。

@click="handleSubmit(onSubmit)"

⇧ の部分については、

vee-validate.logaretm.com

Validating forms before submitting is a must in form validation. The ValidationObserver offers a handleSubmit function that you can use to protect your form submissions. This handleSubmit function accepts a submit handler and will only execute the handler once the user submits a valid form.

https://vee-validate.logaretm.com/v3/guide/forms.html#validate-before-submit

⇧ ということで、handleSubmitは、VeeValidateが用意してる関数らしい。

紛らわしいのが、

lmiller1990.github.io

⇧ 普通のVue.jsのフォームで、

<template>
  <div>
    <form @submit.prevent="handleSubmit">
      <input v-model="username" data-username>
      <input type="submit">
    </form>

    <div 
      class="message" 
      v-if="submitted"
    >
      {{ username }}さん、お問い合わせ、ありがとうございます。
    </div>
  </div>
</template>

<script>
  export default {
    name: "FormSubmitter",

    data() {
      return {
        username: '',
        submitted: false
      }
    },

    methods: {
      handleSubmit() {
        this.submitted = true
      }
    }
  }
</script>

⇧ handleSubmitって名前の関数を自分で定義してたりするという...

npm run serveで開発用サーバーを起動して、Formの入力でバリデーションの確認。

⇧ 正常に入力されてる場合、Createボタン押下で、デベロッパーツールの「Console」タブに表示されてるPromiseのPromiseStateが、"fulfilled" であれば、

const isValid = (this.$refs.observer as any).validate();

⇧ の処理が成功しているということらしいので、バリデーションは正常に実施されたということになるんではないかと。

TypeScriptのサンプルもドキュメントに載せて欲しいかな...

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

今回はこのへんで。