我有一個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,是否有任何特定的文章與示例演示,可能對我有幫助.. –