0

我是 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
);
4

1 回答 1

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 字符,而不仅仅是数字:您需要编辑在“名称”规则中定义的正则表达式。我建议使用这个问题的答案中的正则表达式。所以:用/^[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
);
于 2013-03-05T07:07:58.087 回答