String field validator supports empty strings

It is possible to create a field validator that will make an exception
from the minimal length if the string is empty. And by "make an
exception", I don't mean "throwing one".
This commit is contained in:
Emmanuel BENOîT 2012-02-05 23:03:18 +01:00
parent b80ac7ee91
commit f80d739f5d

View file

@ -7,20 +7,22 @@ class Validator_StringLength
protected $errorPrefix;
protected $minLength;
protected $maxLength;
protected $allowEmpty;
public function __construct( $errorPrefix , $minLength = 0 , $maxLength = null )
public function __construct( $errorPrefix , $minLength = 0 , $maxLength = null , $allowEmpty = false )
{
assert( $maxLength === null || $maxLength >= $minLength );
$this->errorPrefix = $errorPrefix;
$this->minLength = $minLength;
$this->maxLength = $maxLength;
$this->allowEmpty = $allowEmpty;
}
public function validate( $value )
{
$len = strlen( $value );
if ( $len < $this->minLength ) {
if ( $len < $this->minLength && ( $len != 0 || ! $this->allowEmpty ) ) {
$template = Loader::Text( '%1$s is too short (min. %2$d characters)' );
return array( sprintf( $template , $this->errorPrefix , $this->minLength ) );
}