3
3

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.

Vue.js によるリアルタイムフォームバリデーション方法 メモ

Posted at
  • よく見かけるフォーム入力時にリアルタイムでチェック結果を表示する機能をVue.jsで実現する方法についてメモする。

実装例

  • アカウント登録画面でメールアドレスバリデーションを行うケースを想定した実装例。

  • 処理の流れ

    1. メールアドレスプロパティを監視する。

    2. 値の変更を検知し、入力チェックメソッド呼び出す。

    3. チェック結果に合わせてメッセージ表示を行う。

  • フォーム

    • 入力判定結果isValidの値に応じて、エラーメッセージリストerrorsの表示制御を行う。
         <form id="form" v-on:submit.prevent="createUser">
            <input
              type="email"
              v-model="mailaddress"
              placeholder="example@example.com"
            />
            <input
              type="password"
              v-model="password"
            />
            <input type="submit" value="Create User" />
          </form>
    	  <ul v-show="!isValid">
             <li v-for="item in errors" :key="item.message">
                {{ item.message }}
             </li>
          </ul>
    
  • スクリプト

    export default {
      data: function () {
        return {
          mailaddress: "",
          password: "",
          isValid: true,// 入力チェック結果
          errors: [],	// エラーメッセージリスト 
        };
      },
      watch: {
        // メールアドレスプロパティウォッチャ
        mailaddress: function () {
          this.errors = [];
          this.isValid = true;
          // メールアドレス入力チェックメソッド呼び出し
          if (
            !this.checkNotNull(this.mailaddress) ||
            !this.checkFormat(this.mailaddress)
          ) {
            this.isValid = false;
          }
        },
      },
      methods: {
        // メールアドレス入力チェックメソッド:不正な入力の場合、対応するエラーメッセージを格納する。
        // nullチェック
        checkNotNull: function (inputdata) {
          var result = true;
          if (!inputdata) {
            this.errors.push({ message: "メールアドレスを入力してください。" });
            result = false;
          }
          return result;
        },
        // 形式チェック
        checkFormat: function (inputdata) {
          var result = true;
          var re = /^[a-zA-Z0-9_.+-]+@([a-zA-Z0-9][a-zA-Z0-9-]*[a-zA-Z0-9]*\.)+[a-zA-Z]{2,}$/i;
          result = re.test(inputdata);
          if (!result) {
            this.errors.push({ message: "メールアドレス形式で入力してください。" });
          }
          return result;
        },
        ...
    

参考情報

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?