LoginSignup
24
21

More than 5 years have passed since last update.

validatorjsのカスタムルールを書くときの注意点

Posted at

前回フロントサイドのバリデーションにはvalidatorjsが便利を沢山の方に「いいね」して頂いたので、調子に乗って第二弾です。

validatorjsでは当然ながらカスタムルールを追加することができます。
本家のドキュメントによれば

Validator.register(name, callbackFn, errorMessage);

のようにルール名、バリデーションを行うコールバック、エラーメッセージを渡すことになっています。
本家ではサンプルとして、電話番号のバリデーションを行うルールtelephoneの例が載っています。

Validator.register('telephone', function(value, requirement, attribute) { // requirement parameter defaults to null
    return value.match(/^\d{3}-\d{3}-\d{4}$/);
}, 'The :attribute phone number is not in the format XXX-XXX-XXXX.');

さて、問題はこのコールバックのシグネチャです。本家のサンプルコードではvalue, requirement, attributeとなっていますが、実際にコードを組んでみるとちょっと違うようなのです。

本家のコードでは、呼び出し元のコードはこんな感じになっています。

  check: function() {
    var self = this;

    for (var attribute in this.rules) {

      (snip)

      for (var i = 0, len = attributeRules.length, rule, ruleOptions, rulePassed; i < len; i++) {
        ruleOptions = attributeRules[i];

        (snip)

        rulePassed = rule.validate(inputValue, ruleOptions.value, attribute);
        if (!rulePassed) {
          this._addFailure(rule);
        }

        (snip)
      }
    }

    return this.errorCount === 0;
  },
  • 第1引数: (inputValue): データとして入力された値
  • 第2引数: (ruleOptions.value): ルールのオプション
  • 第3引数: (attribute): ルールのキー名

が正しい結果のようですね。

実際に簡単なテストコードを組んでみました。

<html>
    <head>
        <script src="./validatorjs/dist/validator.js"></script>
    </head>

    <body>
        <script>
            Validator.register('telephone', function(value, requirement, attribute) {
                console.log(arguments);
                return value.match(/^\d{3}-\d{3}-\d{4}$/);
            }, 'The :attribute phone number is not in the format XXX-XXX-XXXX.');

            var v = new Validator({
                tel: '012-345-6789'
            }, {
                tel: 'required|telephone:ja'
            });

            console.log(v.check());
        </script>
    </body>
</html>

結果はこんな感じ。
スクリーンショット 2017-03-15 13.54.53.png

第2引数に、telephoneルールに指定したオプションであるjaが渡されていることがわかります。

これを利用すれば、jaオプションを指定した場合のパターンを追加することができますね。

Validator.register('telephone', function(value, option, attribute) {
    var valid_pattern = /^\d{3}-\d{3}-\d{4}$/; 

    // 日本の電話番号のパターン
    // 参考: 総務省 電話番号に関するQ&A
    //       http://www.soumu.go.jp/main_sosiki/joho_tsusin/top/tel_number/q_and_a.html 
    if(option == 'ja'){
        valid_pattern = /^0\d{1,4}-\d{1,4}-\d{4}$/; 
    }

    return valid_pattern.test(value);
}, 'The :attribute phone number is not in the valid format.');

validatorjsはルールの拡張がしやすいのでどんどん活用しましょう。

24
21
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
24
21