Recently whilst building a CakePHP app on a shiny new server I noticed some unexpected behaviour when using an alphaNumeric rule to validate a model. Whatever I passed into the model returned false. That is to say that even a valid alphanumeric string threw up an exception. (if you haven’t already dived into CakePHP, you should – it’s a rapid development framework based on MVC.)
The issue seems to be tied to PHP 5.1.2 and the way regular expressions are handled, however it seems the it may appear in other configurations too. Before I get to a workaround, note I haven’t levelled the “bug” word at either PHP nor CakePHP – for all I know it could be a difference of opinion on how something should be handled. What I do know is that I would rather harness CakePHP’s flexibility to create custom model rules than try upgrading my current live server PHP installation.
Here is an example of how you should be able to implement the alphaNumeric rule using validation in CakePHP based on a simpliefied model called “User”:
class User extends AppModel
{
var $name = 'User';
var $helpers = array('Form');
var $validate = array(
'username' => array(
'loginRule-1' => array(
'rule' => 'alphaNumeric',
'last' => true,
'message' => 'Only letters and numbers allowed'
));
}
The rule in bold italics above is the one that doesn’t always work. However this can be easily rectified with a custom rule built on a regular expression seeking out valid alphanumeric strings.
To achieve this the alphaNumeric rule just needs to be replaced with this:
"rule" => array('custom', '/^[a-z0-9]*$/i'),
Problem solved.