我有一个数据验证类方法,我在将记录插入数据库之前检查用户输入。我想为每个字段方法应用许多规则,例如
现场电子邮件必须验证 以下
a)使用确认电子邮件 FILTER_VALIDATE_EMAIL
b)检查是否存在重复邮件 数据库(这不适用 每次)
字段名称必须验证以下内容。
a)只有空间的a-z或A-Z 允许
b)它应该是最小值5和最大值 40个字符
等我想确保我应该能够为每个字段应用许多规则,它也应该是可选的。
这是我正在使用的原始代码。
public function validate() {
if(!empty($this->name)) {
if(!preg_match('/^[a-zA-z ]{3,50}$/',$this->name)) {
$this->error['name'] = 'Name should be valid letters and should be between 3 and 25 characters';
}
}
if(!empty($this->email)) {
if(!filter_var($this->email,FILTER_VALIDATE_EMAIL)) {
$this->error['invalidEmail'] = 'Invalid email address';
}
if($this->emailCount($this->email)) {
$this->error['emailExist'] = 'Email already exist';
}
}
if(!empty($this->password)) {
$this->password = trim($this->password);
if(strlen($this->password) < 5 || strlen($this->password > 40)) {
$this->error['password'] = 'Password length should be between 5 and 40 characters';
}
}
if(!empty($this->pPhone)) {
if(!preg_match('/^[0-9]{5,10}$/',$this->pPhone)) {
$this->error['invalidpPhone'] = 'Invalid primary phone number';
}
}
if(!empty($this->sPhone)) {
if(!preg_match('/^[0-9]{5,10}$/',$this->sPhone)) {
$this->error['invalidsPhone'] = 'Invalid secondary phone number';
}
}
return (empty($this->error)) ? true : false;
}
而不是使用大量的if条件我想使用带有多维数组的switch case这样的东西。
var $validate = array(
'name' => array(
'notEmpty'=> array(
'rule' => 'notEmpty',
'message' => 'Name can not be blank.'
),
'allowedCharacters'=> array(
'rule' => '|^[a-zA-Z ]*$|',
'message' => 'Name can only be letters.'
),
'minLength'=> array(
'rule' => array('minLength', 3),
'message' => 'Name must be at least 3 characters long.'
),
'maxLength'=> array(
'rule' => array('maxLength', 255),
'message' => 'Name can not be longer that 255 characters.'
)
),
'email' => array(
'email' => array(
'rule' => 'email',
'message' => 'Please provide a valid email address.'
),
'isUnique' => array(
'rule' => 'isUnique',
'message' => 'This E-mail used by another user.'
)
)
);
我对如何实现mt代码以便与后者兼容感到困惑。关于我原来的,如果有人向我展示一个关于用后者实现验证的例子,我将感激不尽。
谢谢。答案 0 :(得分:0)
我会把它放到一些函数中:
// Validation methods
function checkMail($mail) {
// perform mail checks
if(!valid)
throw Exception("not valid mail");
}
function checkMinLength($string) {
// perform length
if(!valid)
throw Exception("not valid length");
}
// mapping fields - methods
$mappingArray = array('mailfield' => array('checkMail'), 'lengthfield' => array('checkMinLength');
// perform checking
try {
foreach($arrayContaintingYourFields as $field) {
foreach($mappingArray[$field['name']] as $check) {
call_user_func($check, $field['value']);
}
}
} catch (Exception $e) {
echo $e->getMessage();
}
您可以通过定义自己的exception types并以不同的方式做出反应来影响错误处理。
} catch (MailException $e) {
echo $e->getMessage();
} catch (LengthException $e) {
// do some other stuff
}