我是cakephp的新手,我正在尝试为程序名称进行数据验证。我希望我的程序名称只允许使用alphaNumeric或字符。我不希望它允许仅数字或特殊字符。实际上,由于第二条规则,不允许使用Numeric或alphaNumeric。这是我的代码
$validate = array(
'program_name' => array(
'required' => array(
'rule' => 'isUnique',
'allowEmpty'=> false,
'message' => 'This Program Name already exists. Please enter a Program Name'
),
'alphaNumeric'=> array(
'rule' => 'alphaNumeric',
'message'=> 'Please enter a valid name'
),
'name' => array(
'rule' => '/^[a-zA-Z]*$/',
'message' => 'Only letters or alphaNumerics. Please enter a valid name')
)
)
//Validation rules for other fields, if any
);
答案 0 :(得分:1)
您对“必需”的使用已关闭,可能应该是这样:
$validate = array(
'program_name' => array(
'isUnique' => array(
'rule' => 'isUnique',
'allowEmpty'=> false,
'required' => true,
'message' => 'This Program Name already exists. Please enter a Program Name'
),
'alphaNumeric'=> array(
'rule' => 'alphaNumeric',
'message'=> 'Please enter a valid name'
),
'name' => array(
'rule' => '/^[a-zA-Z]*$/',
'message' => 'Only letters or alphaNumerics. Please enter a valid name')
)
)
//Validation rules for other fields, if any
);
现在,在修复了“必需”的使用后,我们将继续讨论您的问题。如果要检查字符串是否包含alphaNumeric字符,而不仅仅是数字:您需要编辑“名称”规则中定义的正则表达式。我建议使用this question答案中的正则表达式。
所以:用我提到的帖子中的正则表达式替换/^[a-zA-Z]*$/
,然后删除名为alphaNumeric的规则,所以你的代码如下所示:
$validate = array(
'program_name' => array(
'isUnique' => array(
'rule' => 'isUnique',
'allowEmpty'=> false,
'required' => true,
'message' => 'This Program Name already exists. Please enter a Program Name'
),
'name' => array(
'rule' => '/^(?![0-9]*$)[a-zA-Z0-9]+$/',
'message' => 'Only letters or alphaNumerics. Please enter a valid name')
)
)
//Validation rules for other fields, if any
);