alphaNumericを上書き

CakePHPのalphaNumericチェックにバグがあるようなので改修方法検索。

追加validationルール作るよりも、app_model.phpでalphaNumeric()を上書きしてしまう方がスッキリするし、本線のalphaNumericを使いたくなった場合の取り外しが容易なので、以下を参考に実装

CakePHP 1.2RC3でバリデーションalphaNumericが動かないのを何とかしてみる - しょうこりもなくブログる


実装内容(svnの改修差分)

Index: models/user.php
===================================================================
--- models/user.php     (revision 133)
+++ models/user.php     (working copy)
@@ -5,17 +5,20 @@

        var $validate = array(
                'username' => array(
+                       'alphaNumeric' => array(
+                               'rule' => 'alphaNumeric',
+                       ),
                       'notEmpty' => array(
                                'rule' => 'notEmpty',
                        ),
                ),
Index: models/app_model.php
===================================================================
--- models/app_model.php        (revision 133)
+++ models/app_model.php        (working copy)
@@ -4,13 +4,24 @@

        function beforeValidate(){
                $error_messages = array(
                       'notEmpty'      => __('Please be sure to input.', true),
                       'between' => __('Between %2$d and %3$d characters.', true),
+                       'alphaNumeric' => __('Please input only alphameric characters.',true),
                );
                $this->setErrorMessageI18n($error_messages, false);

                $this->replaceValidationErrorMessagesI18n();
                return true;
        }
+
+       function alphaNumeric($data) {
+               $check = is_array($data) ? array_shift($data) : $data;
+               if (preg_match('/^[0-9a-z]+$/i',$check)) {
+                       return true;
+               } else {
+                       return false;
+               }
+       }
+
 }