diff --git a/src/Valitron/Validator.php b/src/Valitron/Validator.php index b45b69a..d9fe2f7 100644 --- a/src/Valitron/Validator.php +++ b/src/Valitron/Validator.php @@ -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($stop = true) { + $this->stop_on_first_fail = (bool) $stop; + } + /** * Returns all rule callbacks, the static and instance ones. * diff --git a/tests/Valitron/StopOnFirstFailTest.php b/tests/Valitron/StopOnFirstFailTest.php new file mode 100644 index 0000000..656427d --- /dev/null +++ b/tests/Valitron/StopOnFirstFailTest.php @@ -0,0 +1,28 @@ + 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']); + } + +}