我有一个php类的方法,它确定是否一个类属性有任何价值。如果它包含任何值,那么它将验证并迭代$ this-> error类属性。这里是我正在使用的类方法。有没有更好的方法,然后使用多个条件?
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(empty($this->userId) && $this->emailCount($this->email)) {
$this->error['emailExist'] = 'Email already exist';
}
}
if(empty($this->userId) && !empty($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->userId) && !empty($this->newPassword)) {
if(strlen($this->newPassword) < 5 || strlen($this->newPassword > 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;
}
我已经使用很多,如果在这里,我认为情况不是很好,还有没有其他的办法可以判断上述条件并以更更好的方式重写代码?
在我看来,这可能是更好的选择,也易于阅读。谢谢你,会玩弄它。 –
@IbrahimAzharArmar看看CakePHP验证系统。这几乎是相同的原理 – JohnP
@JonhP,是否有任何特定的文章与示例演示,可能对我有帮助.. –