Added option to stop validation when a rule is failed

This commit is contained in:
Julius Ijie 2018-02-23 15:25:35 +01:00
parent 4b32e6067a
commit 6837c9dfab
2 changed files with 47 additions and 0 deletions

View File

@ -77,6 +77,11 @@ class Validator
*/
protected $validUrlPrefixes = array('http://', 'https://', 'ftp://');
/**
* @var bool
*/
protected $stop_on_first_fail = false;
/**
* Setup validation
*
@ -965,6 +970,7 @@ class Validator
*/
public function validate()
{
$set_to_break = false;
foreach ($this->_validations as $v) {
foreach ($v['fields'] as $field) {
list($values, $multiple) = $this->getPart($this->_fields, explode('.', $field));
@ -999,13 +1005,26 @@ class Validator
if (!$result) {
$this->error($field, $v['message'], $v['params']);
if($this->stop_on_first_fail) {
$set_to_break = true;
break;
}
}
}
if($set_to_break) break;
}
return count($this->errors()) === 0;
}
/**
* Should the validation stop a rule is failed
* @param bool $stop
*/
public function stopOnFirstFail(bool $stop) {
$this->stop_on_first_fail = $stop;
}
/**
* Returns all rule callbacks, the static and instance ones.
*

View File

@ -0,0 +1,28 @@
<?php
use Valitron\Validator;
class StopOnFirstFail extends BaseTestCase {
public function testStopOnFirstFail() {
$rules = array(
'myField1' => array(
array('lengthMin', 5, 'message'=>'myField1 must be 5 characters minimum'),
array('url', 'message' => 'myField1 is not a valid url'),
array('urlActive', 'message' => 'myField1 is not an active url')
)
);
$v = new Validator(array(
'myField1' => 'myVal'
));
$v->mapFieldsRules($rules);
$v->stopOnFirstFail(true);
$this->assertFalse($v->validate());
$errors = $v->errors();
$this->assertCount(1, $errors['myField1']);
}
}