问题
I have a description
field in my database which accepts alphanumeric characters and spaces, as well as new line characters. I want to set that validation rule in my Server
model.
Here's what I have now:
<?php
class Server extends AppModel {
public $validate = array(
// ...
'description' => array(
'characters' => array(
'rule' => 'alphaNumeric',
'message' => 'Alphanumeric characters only'
)
),
// ...
);
}
How can I modify this to allow spaces and new lines as well as alphanumeric characters? I thought Cake would have a build in validation rule for this but I can't see one. Do I need to write my own and use some regex?
Thanks.
回答1:
alphaNumeric in CakePHP means alphanumeric characters without spaces. Therefore you have to use your own regex pattern.
Example:
'description' => array(
'characters' => array(
'rule' => array('custom', '/^[a-z0-9 ]*$/i'),
'message' => 'Alphanumeric characters with spaces only'
)
),
回答2:
No, CakePHP can't cover all cases and yours is also not a so common one.
See http://api20.cakephp.org/view_source/validation#l-73 its just chars and integers.
Use
'rule' => array('custom', 'your-regex-here'),
Should be easy to find a regex that matches your need or to copy and modify the one from the validation class.
回答3:
If you take a look at the alphaNumeric function in lib/cake/utility/validation.php you have :
/^[\p{Ll}\p{Lm}\p{Lo}\p{Lt}\p{Lu}\p{Nd}]+$/Du
This matches the alphanumeric unicode letters and digits like Владимир (in russia), 김정 (in korea), 习近平 (in china) etc...
So i made my custom alphanumeric pattern with the default CakePhp and for names like O'Brian, François, Mary-Louise, Juan Martin ...
/^(?![\s'-])(?:[\s'-]{0,1}[\p{Ll}\p{Lm}\p{Lo}\p{Lt}\p{Lu}\p{Nd}])+$/Du
Now it matches names with ', - and spaces. But not if they are consecutive, at the first or last position (because i don't think this can exist^^)
Hope this will help someone :)
Edit : However sometimes it does not accept some accented non latin characters like in cyrilic и́ which is in fact two characters и and ́ . And ́ is in the unicode category of Mark, Nonspacing Mn (and Mn is not in this regex pattern). This kind of exception is not rare in asian languages (chinese, korean, hindi...) beacause there are full of Mn unicode characters.
FD
来源:https://stackoverflow.com/questions/11320691/cakephp-validation-rule-alphanumeric-with-spaces