cakephp validation and regular expressions

谁说胖子不能爱 提交于 2019-12-10 17:14:02

问题


I am working in cakephp1.3. i have to validate my form using cakephp validation in model.i added a regular expression to restrict special characters entry.

My code is written below:

var $validate = array(
        'name' => array(
            'unique'=>array(
                 'rule'      => 'isUnique',
                    'message'   => 'Already taken',
            ),
            'pattern'=>array(
                 'rule'      => '/^[a-z]$/i',
                    'message'   => 'Only letters allowed',
            ),
            'empty'=>array(
                'rule' => 'notEmpty',
                'message' => 'This field cannot be left blank',
            ))
    );

rule 'unique' is not working. it was working fine before i added the 'pattern' rule in script.what is the issue? i try to place the order of rules i mentioned above, i thought there is may be some positioning issue but nothing happened.

plz help me..


回答1:


Replace $ with +:

var $validate = array(
    'name' => array(
        'notempty' => array(
            'rule' => array('notempty'),
            'message' => 'This field cannot be left blank',
        ),
        'unique'=>array(
            'rule' => 'isUnique',
            'message' => 'Already taken'
        ),
        'pattern'=>array(
             'rule'      => '[a-zA-Z]+',
             'message'   => 'Only letters allowed',
        ),
    ),
);



回答2:


You need to precise how long your char can be. Add this data after the «]» :

  • * for 0 or more
  • + for 1 or more
  • ? for 0 or 1
  • {2,9} for a count number between limits
  • {2,} for a minimum only
  • {0,1024} for a maximum only

http://www.php.net/manual/en/regexp.reference.meta.php

exemples :

   'rule'      => '/^[a-z]+$/i',
   'rule'      => '/^[a-z]{3-255}$/i',


来源:https://stackoverflow.com/questions/14500069/cakephp-validation-and-regular-expressions

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!