搜索
首页php教程PHP开发Zend Framework常用校验器详解

本文实例讲述了Zend Framework常用校验器。分享给大家供大家参考,具体如下:

Date日期校验器

代码:

<?php
require_once &#39;Zend/Validate/Date.php&#39;;
function c_date($date){
  $validator = new Zend_Validate_Date();
  if($validator->isValid($date)){
    echo "输入的日期格式:";
    echo $date."有效!<p>";
  }else{
    echo "输入的日期格式:";
    echo $date."无效!<p>";
  }
}
$date1 = "2008-02-15";
$date2 = "2008-02-31";
$date3 = "02-15-2008";
c_date($date1);
c_date($date2);
c_date($date3);

结果:

输入的日期格式:2008-02-15有效!

输入的日期格式:2008-02-31无效!

输入的日期格式:02-15-2008无效!

点评:源码解析

public function isValid($value)
{
    if (!is_string($value) && !is_int($value) && !is_float($value) &&
      !is_array($value) && !($value instanceof Zend_Date)) {
      $this->_error(self::INVALID);
      return false;
    }
    $this->_setValue($value);
    if (($this->_format !== null) || ($this->_locale !== null) || is_array($value) ||
       $value instanceof Zend_Date) {
      require_once &#39;Zend/Date.php&#39;;
      if (!Zend_Date::isDate($value, $this->_format, $this->_locale)) {
        if ($this->_checkFormat($value) === false) {
          $this->_error(self::FALSEFORMAT);
        } else {
          $this->_error(self::INVALID_DATE);
        }
        return false;
      }
    } else {
      if (!preg_match(&#39;/^\d{4}-\d{2}-\d{2}$/&#39;, $value)) {
        $this->_format = &#39;yyyy-MM-dd&#39;;
        $this->_error(self::FALSEFORMAT);
        $this->_format = null;
        return false;
      }
      list($year, $month, $day) = sscanf($value, &#39;%d-%d-%d&#39;);
      if (!checkdate($month, $day, $year)) {
        $this->_error(self::INVALID_DATE);
        return false;
      }
    }
    return true;
}

InArray数组包含校验器

如果内容包含在数组中将返回True,否则返回False。

代码:

<?php
require_once &#39;Zend/Validate/InArray.php&#39;;
function c_array($n){
  $temp = array("北京","上海","天津","重庆");
  $validator = new Zend_Validate_InArray($temp);
  if($validator->isValid($n)){
    echo "指定的内容:";
    echo $n.",存在于指定数组中!<p>";
  }else{
    echo "指定的内容:";
    echo $n.",不存在于指定数组中!<p>";
  }
}
$city1 = "北京";
$city2 = "重庆";
$city3 = "郑州";
c_array($city1);
c_array($city2);
c_array($city3);

结果:

指定的内容:北京,存在于指定数组中!

指定的内容:重庆,存在于指定数组中!

指定的内容:郑州,不存在于指定数组中!

Regex正则匹配校验器

通过使用正则表达式,再加上合理使用本校验器,几乎可以实现所有的校验规则。

代码:

<?php
require_once "Zend/Validate.php";
function c_rege($v){
  $pattern = array("/ab{2,}/");
  if(Zend_Validate::is($v,"Regex",$pattern)){
    echo "<font color=\"#006600\">指定的内容:";
    echo $v."<p>符合定义的正规规则!</font>";
    echo "<p>";
  }else{
    echo "<font color=\"#ff0000\">指定的内容:";
    echo $v."<p>不符合定义的正规规则!</font>";
    echo "<p>";
  }
}
$temp1 = "ab";
$temp2 = "abb";
$temp3 = "abbb";
c_rege($temp1);
c_rege($temp2);
c_rege($temp3);

结果:

指定的内容:ab

不符合定义的正规规则!

指定的内容:abb

符合定义的正规规则!

指定的内容:abbb

符合定义的正规规则!

点评:

public function __construct($pattern)
{
    if ($pattern instanceof Zend_Config) {
      $pattern = $pattern->toArray();
    }
    if (is_array($pattern)) {
      if (array_key_exists(&#39;pattern&#39;, $pattern)) {
        $pattern = $pattern[&#39;pattern&#39;];
      } else {
        require_once &#39;Zend/Validate/Exception.php&#39;;
        throw new Zend_Validate_Exception("Missing option &#39;pattern&#39;");
      }
    }
    $this->setPattern($pattern);
}

构造函数初始化私有属性,

public function isValid($value)
{
    if (!is_string($value) && !is_int($value) && !is_float($value)) {
      $this->_error(self::INVALID);
      return false;
    }
    $this->_setValue($value);
    $status = @preg_match($this->_pattern, $value);
    if (false === $status) {
      $this->_error(self::ERROROUS);
      return false;
    }
    if (!$status) {
      $this->_error(self::NOT_MATCH);
      return false;
    }
    return true;
}

进行验证工作。

自定义校验器编写

继承Zend_Validate_Interface接口实现用户自定义校验器。

代码案例,功能判断指定数值是否为3的倍数。

接口代码:

<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category  Zend
 * @package  Zend_Validate
 * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
 * @license  http://framework.zend.com/license/new-bsd   New BSD License
 * @version  $Id: Interface.php 24593 2012-01-05 20:35:02Z matthew $
 */
/**
 * @category  Zend
 * @package  Zend_Validate
 * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
 * @license  http://framework.zend.com/license/new-bsd   New BSD License
 */
interface Zend_Validate_Interface
{
  /**
   * Returns true if and only if $value meets the validation requirements
   *
   * If $value fails validation, then this method returns false, and
   * getMessages() will return an array of messages that explain why the
   * validation failed.
   *
   * @param mixed $value
   * @return boolean
   * @throws Zend_Validate_Exception If validation of $value is impossible
   */
  public function isValid($value);
  /**
   * Returns an array of messages that explain why the most recent isValid()
   * call returned false. The array keys are validation failure message identifiers,
   * and the array values are the corresponding human-readable message strings.
   *
   * If isValid() was never called or if the most recent isValid() call
   * returned true, then this method returns an empty array.
   *
   * @return array
   */
  public function getMessages();
}

要实现其中的两个方法,一个是isValid(),一个是getMessages()

实现代码:

<?php
require_once "Zend/Validate/Interface.php";
class MyValidator implements Zend_Validate_Interface{
  protected $_messages = array();
  public function isValid($value){
    $this->_messages = array();
    $requirement = !($value%3);
    if(!$requirement){
      $this->_messages[] = "&#39;$value&#39;不能被3整除";
      return false;
    }
    return true;
  }
  public function getMessages(){
    return $this->_messages;
  }
}
function c_n_3($n){
  $validator = new MyValidator();
  if($validator->isValid($n)){
    echo "指定的数值:";
    echo $n.",是3的倍数!<p>";
  }else{
    echo "指定的数值:";
    echo $n.",不是3的倍数!<p>";
    echo "失败的消息为:<p>";
    foreach ($validator->getMessages() as $message) {
      echo "$message<p>";
    }
  }
}
$num1 = 5;
$num2 = 6;
$num3 = 8;
c_n_3($num1);
c_n_3($num2);
c_n_3($num3);

结果:

指定的数值:5,不是3的倍数!

失败的消息为:

'5'不能被3整除

指定的数值:6,是3的倍数!

指定的数值:8,不是3的倍数!

失败的消息为:

'8'不能被3整除

点评:

这里通过isValid()方法来设置属性信息,通过getMessages()方法来获取错误消息。错误消息是一个数组,通过foreach()方法来遍历读取。

希望本文所述对大家基于Zend Framework框架的PHP程序设计有所帮助。

更多Zend Framework常用校验器详解相关文章请关注PHP中文网!

声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

AI Hentai Generator

AI Hentai Generator

免费生成ai无尽的。

热门文章

R.E.P.O.能量晶体解释及其做什么(黄色晶体)
4 周前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳图形设置
4 周前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.如果您听不到任何人,如何修复音频
4 周前By尊渡假赌尊渡假赌尊渡假赌
WWE 2K25:如何解锁Myrise中的所有内容
1 个月前By尊渡假赌尊渡假赌尊渡假赌

热工具

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具

安全考试浏览器

安全考试浏览器

Safe Exam Browser是一个安全的浏览器环境,用于安全地进行在线考试。该软件将任何计算机变成一个安全的工作站。它控制对任何实用工具的访问,并防止学生使用未经授权的资源。

SublimeText3 Linux新版

SublimeText3 Linux新版

SublimeText3 Linux最新版

螳螂BT

螳螂BT

Mantis是一个易于部署的基于Web的缺陷跟踪工具,用于帮助产品缺陷跟踪。它需要PHP、MySQL和一个Web服务器。请查看我们的演示和托管服务。

WebStorm Mac版

WebStorm Mac版

好用的JavaScript开发工具