使用多维数组进行数据验证

发布于 2024-11-07 03:50:49 字数 2876 浏览 0 评论 0原文

我有一个数据验证类方法,在将记录插入数据库之前检查用户输入。我想对每个字段方法应用许多规则,例如

字段电子邮件必须验证 下列的

a) 使用以下方式验证电子邮件 FILTER_VALIDATE_EMAIL

b) 检查是否存在重复邮件 数据库(这不适用 每次)

字段名称应该验证以下内容。

a) 只有 az 或带空格的 AZ 是 允许

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 代码以与后一个兼容感到困惑。关于我的原始版本,如果有人向我展示一个关于使用后一个版本实施验证的示例,我将不胜感激。

谢谢。

i have a data validation class method where i check the user input before inserting the records into the database. i would like to apply many rules per field method for example

field email will have to validate the
following

a) validate email using
FILTER_VALIDATE_EMAIL

b) check if duplicate mail exist in
database(this does not apply
everytime)

field name should have to validate the following.

a) only a-z or A-Z with space are
allowed

b) it should be minimum 5 and maximum
40 characters

and so on i would want to make sure that i should be able to apply many rules per field and it should be optional as well.

here is the original code i was 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($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;    
}

instead of using lots of if condition i want to use switch case with multi dimensional array with something like this.

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.'
        )
    )        
); 

i am getting confused on how to implement mt code to be compatible with the later one. with regard to my original i will be thankful if someone demonstrate me with an example about implementing validation with the later one.

thank you.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

七分※倦醒 2024-11-14 03:50:49

我会将其放入一些函数中:

// 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();
}

您可以通过定义自己的 异常类型并以不同的方式做出反应。

} catch (MailException $e) {
   echo $e->getMessage();
} catch (LengthException $e) {
   // do some other stuff
}

I would put this into some functions:

// 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();
}

You can influence the error handling by defining own exception types and reacting in different ways.

} catch (MailException $e) {
   echo $e->getMessage();
} catch (LengthException $e) {
   // do some other stuff
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文