www.pokeroconnor.com

Zend Form Validators

May1

I have another post with info on Zend validators, but here’s a very handy class to specify a maximum and minimum value to validate against. E.g. you have a form value that must be between 1 and 10 – Zend Validate doesn’t have a validator for that, but this class will allow you to. Just set $minimum and $maximum to your limits.


class MyValidNumericBetween extends Zend_Validate_Abstract
{
const MSG_NUMERIC = 'msgNumeric';
const MSG_MINIMUM = 'msgMinimum';
const MSG_MAXIMUM = 'msgMaximum';

public $minimum = 1;
public $maximum = 45;

protected $_messageVariables = array(
'min' => 'minimum',
'max' => 'maximum'
);

protected $_messageTemplates = array(
self::MSG_NUMERIC => "'%value%' is not numeric",
self::MSG_MINIMUM => "'%value%' must be at least '%min%'",
self::MSG_MAXIMUM => "'%value%' must be no more than '%max%'"
);

public function isValid($value)
{
$this->_setValue($value);

if (!is_numeric($value)) {
$this->_error(self::MSG_NUMERIC);
return false;
}

if ($value < $this->minimum) {
$this->_error(self::MSG_MINIMUM);
return false;
}

if ($value > $this->maximum) {
$this->_error(self::MSG_MAXIMUM);
return false;
}

 

 

 

return true;
}
}

And to use this class, assuming you have a normal form instantiated with $form = new Zend_Form(), just do:


$custom_valid8r = new MyValidNumericBetween();

$ball1 = $form->createElement('text', 'ball1')
->addValidator($custom_valid8r)
->setRequired(true);

And to set a custom message here are 2 links with good examples, some of them re-printed below.
Firstly:

$validator = new Zend_Validate_StringLength(8);

$validator->setMessage(
'The string \'%value%\' is too short; it must be at least %min% ' .
'characters',
Zend_Validate_StringLength::TOO_SHORT);

if (!$validator->isValid('word')) {
$messages = $validator->getMessages();
echo current($messages);

// "The string 'word' is too short; it must be at least 8 characters"
}


Secondly:

$validator = new Zend_Validate_StringLength(8, 12);

$validator->setMessages( array(
Zend_Validate_StringLength::TOO_SHORT =>
'The string \'%value%\' is too short',
Zend_Validate_StringLength::TOO_LONG =>
'The string \'%value%\' is too long'
));

$validator = new Zend_Validate_StringLength(8, 12);

 

 

if (!validator->isValid('word')) {
echo 'Word failed: '
. $validator->value
. '; its length is not between '
. $validator->min
. ' and '
. $validator->max
. "\n";
}

posted under php

Email will not be published

Website example

Your Comment: