drphfy1198 2011-05-12 05:55
浏览 67
已采纳

有没有更好的方法然后使用多个if条件?

i have a php class method which determines whether if a class property have got any value. if it holds any value then it will validate and iterate $this->error class property. here is the class method i am using.

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;    
}

i have used lots of if conditions here which i think is not very good, is there any other way i could determine the above condition and rewrite the code in a more better way?

  • 写回答

6条回答 默认 最新

  • duanbo5230 2011-05-12 06:13
    关注

    You could use variable variables and loop through your code. But this means you'll have to come up with some sort of standardized validation scheme for your code

    $validateFields = array('email', 'username', 'userId'); //list of fields to validate
    $rules = array(
      'username' => array('type'=> 'regex', 'rule' => '/^[a-zA-z ]{3,50}$/'),
      'email'    => array('type' => 'filter', 'rule' => 'FILTER_VALIDATE_EMAIL')
    );
    
    foreach ($validateFields as $field) {
       if (isset($rules[$field])) {
           switch ($rules[$field]['type']) {
               case 'regex' : 
                  if(!preg_match($rules[$field]['type']['rule'],$this->$field)) {
                        $this->error[$field] = ucfirst($field) . ' should be valid letters and should be between 3 and 25 characters';
                  }
                  break;
    
               case 'filter' :
                  if(!filter_var($this->$field, $rules[$field]['type']['rule'])) {
                      $this->error[$field] = 'Invalid email address';
                  }
                  break
    
               //more cases
           }
       }
    }
    return (empty($this->error)) ? true : false; 
    

    This example only uses one rule per field, but you should be able to easily extend it to use multiple rules per field.

    You'll initially have to setup all the rules, but the validation won't grow just because you add another property to your class.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(5条)

报告相同问题?

悬赏问题

  • ¥15 从Freecad中宏下载的DesignSPHysics,出现如下问题是什么原因导致的(语言-python)
  • ¥30 notepad++ 自定义代码补全提示
  • ¥15 MATLAB有限差分法解一维边值问题
  • ¥200 内网渗透测试 横向渗透 Windows漏洞 Windows权限维持
  • ¥15 数据结构图的相关代码实现
  • ¥15 python中aiohttp.client_exceptions.ContentTypeError
  • ¥30 DeepLung肺结节检测生成最大froc值对应的epoch报错
  • ¥15 信号发生器如何将频率调大,步尽值改成10
  • ¥15 keil 5 编程智能家具,风扇台灯开关,人体感应等
  • ¥100 找一名渗透方面的专家