I looked up how to create custom validators in Symfony1.4, practiced it, so here’s a memo.
First, before creating a custom validator, check if the validator you want to use doesn’t already exist among the existing ones.
・symfony Forms in Action | 付録 B - バリデータ | symfony | Web PHP Framework (symfony Forms in Action | Appendix B - Validators | symfony | Web PHP Framework)
If the validator you want doesn’t exist, create your own.
The articles that were helpful when creating custom validators for Symfony1.4 are as follows:
・The More with symfony book | カスタムウィジェットとバリデータ | symfony | Web PHP Framework (The More with symfony book | Custom Widgets and Validators | symfony | Web PHP Framework)
・symfonyでカスタムバリデータを使ってフィルタを実装する - spanstyle::monolog (Implementing Filters Using Custom Validators in symfony - spanstyle::monolog)
・symfonyのValidatorで全角/半角変換などを行う - ゆっくりゆっくり (Performing Full-width/Half-width Conversion etc. with symfony Validator - SlowlySlowly)
I actually created a validator to check the length and character composition of input values for ISBN, which is a number used to identify books.
By the way, ISBN-10 is 10 digits, with the first digit being 0-9 or X, and other digits being numbers. ISBN-13 is 13 digits, composed only of numbers.
・Reference: ISBN - Wikipedia
I referred to this for regular expression usage:
・正規表現 | PHP Labo (Regular Expressions | PHP Labo)
・正規表現 (Regular Expressions)
And here’s the source I actually created:
■ myValidatorIsbn.class.php
(Validator to check if it matches ISBN format)
$value));
}
}
// If input value length is 13 characters, return input value as is
if (strlen($value) == 13){
// ISBN-13 is composed only of numbers
if (preg_match("/^[0-9]{13}?$/" ,$value))
{
return $value;
} else {
throw new sfValidatorError($this, 'ISBN-13は数字のみで入力して下さい', array('value' => $value));
}
}
// Otherwise, error
throw new sfValidatorError($this, 'ISBNは10文字、または13文字で入力して下さい', array('value' => $value));
}
}
■ IsbnSearchForm.class.php
(Form file defining ISBN input form)
setWidgets(array(
'isbn' => new sfWidgetFormInput(array(), array('size' => 20, 'maxlength' => 13, )),
));
$this->setValidators(array(
'isbn' => new myValidatorIsbn(array('required' => true, ),
array('required' => '未入力', )),
));
$this->widgetSchema->setNameFormat('isbn_search[%s]');
$this->widgetSchema->setLabels(array('isbn' => 'ISBN10/13', ));
}
}
That’s all from the Gemba.