mirror of
https://github.com/vlucas/valitron.git
synced 2025-12-31 07:01:54 +00:00
Merge pull request #140 from MaJerle/master
Added "optional" rule validation: with this rule if a value is provided it will be validated, even if it's an empty string
This commit is contained in:
commit
4112b40452
@ -731,6 +731,12 @@ class Validator
|
|||||||
return $isInstanceOf;
|
return $isInstanceOf;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
//Validate optional field
|
||||||
|
protected function validateOptional($field, $value, $params) {
|
||||||
|
//Always return true
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Get array of fields and data
|
* Get array of fields and data
|
||||||
*
|
*
|
||||||
@ -868,7 +874,9 @@ class Validator
|
|||||||
list($values, $multiple) = $this->getPart($this->_fields, explode('.', $field));
|
list($values, $multiple) = $this->getPart($this->_fields, explode('.', $field));
|
||||||
|
|
||||||
// Don't validate if the field is not required and the value is empty
|
// Don't validate if the field is not required and the value is empty
|
||||||
if ($v['rule'] !== 'required' && !$this->hasRule('required', $field) && (! isset($values) || $values === '' || ($multiple && count($values) == 0))) {
|
if ($this->hasRule('optional', $field) && isset($values)) {
|
||||||
|
//Continue with execution below if statement
|
||||||
|
} elseif ($v['rule'] !== 'required' && !$this->hasRule('required', $field) && (! isset($values) || $values === '' || ($multiple && count($values) == 0))) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@ -1085,6 +1085,27 @@ class ValidateTest extends BaseTestCase
|
|||||||
),
|
),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public function testOptionalProvidedValid()
|
||||||
|
{
|
||||||
|
$v = new Validator(array('address' => 'user@example.com'));
|
||||||
|
$v->rule('optional', 'address')->rule('email', 'address');
|
||||||
|
$this->assertTrue($v->validate());
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testOptionalProvidedInvalid()
|
||||||
|
{
|
||||||
|
$v = new Validator(array('address' => 'userexample.com'));
|
||||||
|
$v->rule('optional', 'address')->rule('email', 'address');
|
||||||
|
$this->assertFalse($v->validate());
|
||||||
|
}
|
||||||
|
|
||||||
|
public function testOptionalNotProvided()
|
||||||
|
{
|
||||||
|
$v = new Validator(array());
|
||||||
|
$v->rule('optional', 'address')->rule('email', 'address');
|
||||||
|
$this->assertTrue($v->validate());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function sampleFunctionCallback($field, $value, array $params) {
|
function sampleFunctionCallback($field, $value, array $params) {
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user