结果:
指定的内容:ab
不符合定义的正规规则!
指定的内容:abb
符合定义的正规规则!
指定的内容:abbb
符合定义的正规规则!
点评:
public function __construct($pattern)
{
if ($pattern instanceof Zend_Config) {
$pattern = $pattern->toArray();
}
if (is_array($pattern)) {
if (array_key_exists('pattern', $pattern)) {
$pattern = $pattern['pattern'];
} else {
require_once 'Zend/Validate/Exception.php';
throw new Zend_Validate_Exception("Missing option 'pattern'");
}
}
$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();
}







