Zend Framework校验器Zend_Validate用法详解
本文实例讲述了ZendFramework校验器Zend_Validate用法。分享给大家供大家参考,具体如下:
引言:
是对输入内容进行检查,并生成一个布尔结果来表明内容是否被成功校验的机制。
如果isValid()方法返回False,子类的getMessage()方法将返回一个消息数组来解释校验失败的原因。
为了正确地返回消息与错误内容,对于isValid()方法的每次调用,都需要清除前一个isValid()方法调用所导致的消息和错误。
案例:
<?php
require_once'Zend/Validate/EmailAddress.php';
functionc_email($email)
{
$validator=newZend_Validate_EmailAddress();
if($validator->isValid($email)){
echo"输入的E-mail地址:";
echo$email."有效!<p>";
}else{
echo"输入的E-mail地址:";
echo$email."无效!";
echo"失败消息为:<p>";
foreach($validator->getMessages()as$message){
echo$message."<p>";
}
foreach($validator->getErrors()as$error){
echo$error."<p>";
}
}
}
$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'isnotavalidemailaddressinthebasicformatlocal-part@hostname
emailAddressInvalidFormat
说明:
在引入类之后,定义一个验证函数,在函数中实例化类。用isValid()方法来进行验证,不同的子类验证器验证的内容是不一样的。
同时通过getMessages()方法和getErrors()方法来。
源码赏析:
publicfunctionisValid($value)
{
if(!is_string($value)){
$this->_error(self::INVALID);
returnfalse;
}
$matches=array();
$length=true;
$this->_setValue($value);
//Splitemailaddressupanddisallow'..'
if((strpos($value,'..')!==false)or
(!preg_match('/^(.+)@([^@]+)$/',$value,$matches))){
$this->_error(self::INVALID_FORMAT);
returnfalse;
}
$this->_localPart=$matches[1];
$this->_hostname=$matches[2];
if((strlen($this->_localPart)>64)||(strlen($this->_hostname)>255)){
$length=false;
$this->_error(self::LENGTH_EXCEEDED);
}
//Matchhostnamepart
if($this->_options['domain']){
$hostname=$this->_validateHostnamePart();
}
$local=$this->_validateLocalPart();
//Ifbothpartsvalid,returntrue
if($local&&$length){
if(($this->_options['domain']&&$hostname)||!$this->_options['domain']){
returntrue;
}
}
returnfalse;
}
解析:
这是主要的验证函数内容,分成了多种情况进行验证,有是否字符串,有是否符合邮箱规则,有长度是否符合,最终都符合才返回true。
更多关于zend相关内容感兴趣的读者可查看本站专题:《ZendFrameWork框架入门教程》、《php优秀开发框架总结》、《Yii框架入门及常用技巧总结》、《ThinkPHP入门教程》、《php面向对象程序设计入门教程》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总》
希望本文所述对大家基于ZendFramework框架的PHP程序设计有所帮助。