Merge pull request #241 from realjay007/stop-on-first-fail

Added option to stop validation when a rule is failed
This commit is contained in:
Willem Wollebrants 2018-03-08 16:48:01 +01:00 committed by GitHub
commit c56bf573f2
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 47 additions and 0 deletions

View File

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