8 * This source file is subject to the new BSD license that is bundled
9 * with this package in the file LICENSE.txt.
10 * It is also available through the world-wide-web at this URL:
11 * http://framework.zend.com/license/new-bsd
12 * If you did not receive a copy of the license and are unable to
13 * obtain it through the world-wide-web, please send an email
14 * to license@zend.com so we can send you a copy immediately.
17 * @package Zend_Validate
18 * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com)
19 * @license http://framework.zend.com/license/new-bsd New BSD License
20 * @version $Id: Ean13.php 16223 2009-06-21 20:04:53Z thomas $
25 * @see Zend_Validate_Abstract
27 require_once 'Zend/Validate/Abstract.php';
32 * @package Zend_Validate
33 * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com)
34 * @license http://framework.zend.com/license/new-bsd New BSD License
36 class Zend_Validate_Barcode_Ean13
extends Zend_Validate_Abstract
39 * Validation failure message key for when the value is
42 const INVALID
= 'invalid';
45 * Validation failure message key for when the value is
46 * not 13 characters long
48 const INVALID_LENGTH
= 'invalidLength';
51 * Validation failure message key for when the value
52 * does not only contain numeric characters
54 const NOT_NUMERIC
= 'ean13NotNumeric';
57 * Validation failure message template definitions
61 protected $_messageTemplates = array(
62 self
::INVALID
=> "'%value%' is an invalid EAN-13 barcode",
63 self
::INVALID_LENGTH
=> "'%value%' should be 13 characters",
64 self
::NOT_NUMERIC
=> "'%value%' should contain only numeric characters",
68 * Defined by Zend_Validate_Interface
70 * Returns true if and only if $value contains a valid barcode
72 * @param string $value
75 public function isValid($value)
77 if (!is_string($value) ||
!ctype_digit($value)) {
78 $this->_error(self
::NOT_NUMERIC
);
82 $this->_setValue($value);
83 if (strlen($value) !== 13) {
84 $this->_error(self
::INVALID_LENGTH
);
88 $barcode = strrev(substr($value, 0, -1));
92 for ($i = 0; $i < 12; $i++
) {
94 $oddSum +
= $barcode[$i] * 3;
95 } elseif ($i %
2 === 1) {
96 $evenSum +
= $barcode[$i];
100 $calculation = ($oddSum +
$evenSum) %
10;
101 $checksum = ($calculation === 0) ?
0 : 10 - $calculation;
103 if ($value[12] != $checksum) {
104 $this->_error(self
::INVALID
);