A. *_* M. 1 php validation cakephp unique
当我从注册表单中保存信息时,我在用户名和电子邮件字段上有一些验证规则(我已粘贴下面的规则).使用saveAll()函数自动调用验证.
问题是用户名字段上的isUnique规则根本不起作用(不返回任何错误).此字段的其他规则工作正常,电子邮件字段的唯一验证也有效.当两条规则基本相同时,我似乎无法弄清楚为什么会发生这种情况.
var $validate = array(
'username' => array(
'isUnique' => array (
'rule' => 'isUnique',
'message' => 'This username already exists.'),
'custom' => array (
'rule' => array('custom', '/^[A-Za-z0-9,\.-_]*$/i'),
'message' => 'The username can only contain letters, numbers, _, - and .'),
'minLength' => array(
'rule' => VALID_NOT_EMPTY,
'message' => 'You must fill in the username.')
),
'email' => array(
'isUnique' => array (
'rule' => 'isUnique',
'message' => 'This email address already exists in our database.'),
'valid' => array (
'rule' => array('email', false),
'message' => 'Invalid email.'),
'minLength' => array(
'rule' => VALID_NOT_EMPTY,
'message' => 'You must fill in the email address.')
)
);
Run Code Online (Sandbox Code Playgroud)
"isUnique"规则在其他行中查找重复值.如果"isUnique"测试也是主键,那将会产生问题.因此,根据您上面的规则/模型,如果您在运行规则时查看SQL转储,您可能会看到类似的内容
SELECT COUNT(*) FROM users WHERE username = 'x' AND username != 'x'
Run Code Online (Sandbox Code Playgroud)
这显然在测试中返回0或"唯一".修复方法是将主键设置为等于您正在测试规则的字段以外的其他内容.当你这样做时,SQL转储应该显示类似的东西
SELECT COUNT(*) FROM users WHERE username = 'x' AND key != 'y'
Run Code Online (Sandbox Code Playgroud)
当字段不唯一并且将恢复所需的功能时,这将返回> 0.