Zend_Validate 校验器概述
本示例详细解析了 Zend Framework 中校验器组件 Zend_Validate 的具体使用方式,旨在为相关开发者提供参考与借鉴。
引言:
该机制用于对输入数据进行合法性检查,并生成一个布尔型结果以表明数据是否通过了校验。
当 isValid() 方法返回 False 时,子类提供的 getMessage() 方法将返回一个包含错误解释的消息数组,说明校验失败的具体原因。
为了确保每次调用都能正确返回当前的消息与错误内容,必须在每次调用 isValid() 之前清除上一次调用所遗留的消息和错误状态。
案例:
<?php
require_once 'Zend/Validate/EmailAddress.php';
function c_email($email)
{
$validator = new Zend_Validate_EmailAddress();
if($validator->isValid($email)){
echo "输入的E-mail地址:";
echo $email."有效!";
}else{
echo "输入的E-mail地址:";
echo $email."无效!";
echo "失败消息为:
";
foreach($validator->getMessages() as $message){
echo $message."
";
}
foreach($validator->getErrors() as $error){
echo $error."
";
}
}
}
$e_m1 = "abc@123.com";
$e_m2 = "abc#123.com";
c_email($e_m1);
c_email($e_m2);
运行结果:
输入的 E-mail 地址:abc@123.com 有效! 输入的 E-mail 地址:abc#123.com 无效!失败消息为: 'abc#123.com' is not a valid email address in the basic format local-part@hostname emailAddressInvalidFormat
说明:
在使用前需引入相应类,并在自定义函数中实例化该类。利用 isValid() 方法执行验证,不同子类的验证器针对的内容各不相同。同时,借助 getMessages() 和 getErrors() 方法来获取详细的验证反馈。
源码赏析:
public function isValid($value)
{
if (!is_string($value)) {
$this->_error(self::INVALID);
return false;
}
$matches = array();
$length = true;
$this->_setValue($value);
// Split email address up and disallow '..'
if ((strpos($value, '..') !== false) or
(!preg_match('/^(.+)@([^@]+)$/', $value, $matches))) {
$this->_error(self::INVALID_FORMAT);
return false;
}
$this->_localPart = $matches[1];
$this->_hostname = $matches[2];
if ((strlen($this->_localPart) > 64) || (strlen($this->_hostname) > 255)) {
$length = false;
$this->_error(self::LENGTH_EXCEEDED);
}
// Match hostname part
if ($this->_options['domain']) {
$hostname = $this->_validateHostnamePart();
}
$local = $this->_validateLocalPart();
// If both parts valid, return true
if ($local && $length) {
if (($this->_options['domain'] && $hostname) || !$this->_options['domain']) {
return true;
}
}
return false;
}
解析:
这是核心的验证函数逻辑,涵盖了多种情况的判断,包括检查是否为字符串、是否符合邮箱规则以及长度是否合规等,只有所有条件均满足时才返回 true。
希望本文所述内容能对基于 Zend Framework 框架的 PHP 程序设计工作有所帮助。