0
0

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.

form通用、jquery.validate.min.jsで項目の入力チェック仕組み

Posted at
sample.html
<link href="css/custom.min.css" rel="stylesheet" /><!--.my-error{color:red}-->
xxx
<input name="XXX" type="text" class="form-control" />
xxx
<script src="js/jquery.validate.min.js" type="text/javascript"></script>
<script src="js/formValidator.js" type="text/javascript"></script>

formValidator.js
// JavaScript Document
// 各画面入力の共通チェックなど
// 効率的に共通化観点で、なるべく以下の観点で設計しましょう:
//     ① 各画面に同じ項目であれば、該当項目の「name」属性を同様に設定する。
//     ② 

(function () {
    //標準エラーメッセージの変更
    $.extend($.validator.messages, {
        email: '*正しいメールアドレスの形式で入力して下さい',
        required: '*入力必須です',
        phone: '*正しい電話番号の形式で入力して下さい',
        hankaku: '*半角0-9,a-z,A-Zで入力して下さい',
        hankakuNumOnly: '*半角0-9で入力して下さい',
        hankakuEngOnly: '*半角a-z,A-Zで入力して下さい'
    });

    //追加ルールの定義
    var methods = {
        phone: function (value, element) {
            return this.optional(element) || /^\d{11}$|^\d{3}-\d{4}-\d{4}$/.test(value);
        },
        hankaku: function (value, element) {
            return this.optional(element) || /^[0-9a-zA-Z]*$/.test(value);
        },
        hankakuNumOnly: function (value, element) {
            return this.optional(element) || /^[0-9]+$/.test(value);
        },
        hankakuEngOnly: function (value, element) {
            return this.optional(element) || /^[a-zA-Z]+$/.test(value);
        }
    };

    //入力項目の検証ルール定義
    var rules = {
        XXX: {
            required: true
        },
        name2: {
            required: true
        },
        name3: {
            hankakuNumOnly: true
        },
    };

    //入力項目ごとのエラーメッセージカスタマイズ
    var messages = {
        name2: {
            required: '*選択して下さい'
        }
    };

    //メソッドの追加
    $.each(methods, function (key) {
        $.validator.addMethod(key, this);
    });

    $('form').each(function () {
        $(this).validate({
            rules: rules,
            messages: messages,

            errorClass: 'my-error',
            errorPlacement: function (error, element) {
                error.insertAfter(element);
            }
        });
    });
})();
0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?