mirror of
https://github.com/vlucas/valitron.git
synced 2025-12-30 23:01:52 +00:00
Added support for non-mandatory fields. Fixes issue #13.
This commit is contained in:
parent
7a0a4a3039
commit
81978ef8c7
@ -498,6 +498,11 @@ class Validator
|
||||
foreach($v['fields'] as $field) {
|
||||
$value = isset($this->_fields[$field]) ? $this->_fields[$field] : null;
|
||||
|
||||
// Don't validate if the field is not required and the value is empty
|
||||
if ($v['rule'] !== 'required' && !$this->hasRule('required', $field) && $value == '') {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Callback is user-specified or assumed method on class
|
||||
if(isset(static::$_rules[$v['rule']])) {
|
||||
$callback = static::$_rules[$v['rule']];
|
||||
@ -511,9 +516,22 @@ class Validator
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return count($this->errors()) === 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine whether a field is being validated by the given rule.
|
||||
*
|
||||
* @param string $name The name of the rule
|
||||
* @param string $field The name of the field
|
||||
* @return boolean
|
||||
*/
|
||||
protected function hasRule($name, $field)
|
||||
{
|
||||
return isset($this->_validations[$name]) && in_array($field, $this->_validations[$name]['fields']);
|
||||
}
|
||||
|
||||
/**
|
||||
* Register new validation rule callback
|
||||
*/
|
||||
|
||||
@ -63,7 +63,7 @@ class ValidateTest extends \PHPUnit_Framework_TestCase
|
||||
'email' => array('Email should be a valid email address')
|
||||
);
|
||||
|
||||
$v = new Validator(array());
|
||||
$v = new Validator(array('name' => '', 'email' => '$'));
|
||||
$v->rule('required', 'name')->message('{field} is required');
|
||||
$v->rule('email', 'email')->message('{field} should be a valid email address');
|
||||
|
||||
@ -128,7 +128,7 @@ class ValidateTest extends \PHPUnit_Framework_TestCase
|
||||
|
||||
public function testDifferentInvalid()
|
||||
{
|
||||
$v = new Validator(array('test1' => 'test', 'test2' => 'test'));
|
||||
$v = new Validator(array('foo' => 'baz', 'bar' => 'baz'));
|
||||
$v->rule('different', 'foo', 'bar');
|
||||
$this->assertFalse($v->validate());
|
||||
}
|
||||
@ -385,6 +385,16 @@ class ValidateTest extends \PHPUnit_Framework_TestCase
|
||||
$this->assertFalse($v->validate());
|
||||
}
|
||||
|
||||
/**
|
||||
* @group issue-13
|
||||
*/
|
||||
public function testDateValidWhenEmptyButNotRequired()
|
||||
{
|
||||
$v = new Validator(array('date' => ''));
|
||||
$v->rule('date', 'date');
|
||||
$this->assertTrue($v->validate());
|
||||
}
|
||||
|
||||
public function testDateFormatValid()
|
||||
{
|
||||
$v = new Validator(array('date' => '2013-01-27'));
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user