问题
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