Tuesday, October 27, 2009

Validators in ZedSeriesWizard

About writing validators using ZedSeriesWizard

note

before reading this be sure to read and understand Getting started with ZedSeriesWizard

Built-in validators

Since ZedSeriesWizard uses standard TYPOlight widgets we can take advantage of them. Please refer to http://www.typolight.org/reference.html#evaluation (rgxp section) for a list of built-in validators.

Custom validators

Sometimes the built-in validators does not fulfill our requirements, fortunately we can specify custom validators. We are going to add the following condition to MyFirstWizard:

These are our validation requirements:

  • The fullname must begins with an "a"
  • The age must be in the range 20, 25
  • The email must not ends with a .info domain

note

if you think these requirements are eccentric, I agree with you :)

Adding validators to MyFirstWizard

First of all let's create our validator class:

methods used for validation have the following signature:

public function myValidatorMethod(Widget $w)

take a look at http://api.typolight.org/ for more information about the Widget class

<?php
class MyFirstWizardValidator {

public function validateName(Widget $w) {
$firstLetter = substr($w->value, 0, 1);

if (strtolower($firstLetter) != 'a') {
$w->addError('Fullname must begins with a');
}
}

public function ageCheck(Widget $w) {
if ($w->value < 20 || $w->value > 25 ) {
$w->addError('Your age does not fulfill the requirements');
}
}

public function validateEmail(Widget $w) {
$emailParts = explode('.', $w->value);
$domain = array_pop($emailParts);

if ($domain == 'info') {
$w->addError('email with domain ".info" are not allowed');
}
}

}



Now it is time to write MyFirstWizard->getValidators in order to use the MyFirstWizardValidator class.




getValidators may returns an associative array where the keys are the fields that must be validated and the values are array callback (like the ones used in DCA, e.g. options_callback)






<?php
// inside MyFirstWizard class ...

protected function getValidators() {
$objValidator = new MyFirstWizardValidator();

return array(
'fullname' => array($objValidator, 'validateName'),
'age' => array($objValidator, 'ageCheck'),
'email' => array($objValidator, 'validateEmail')
);
}



That is! Our wizard now features custom validation.

No comments:

Post a Comment