From 95818c507fd2a7fc2b11b71407338f23776cddee Mon Sep 17 00:00:00 2001 From: Ben Claar Date: Tue, 24 Jul 2018 15:35:46 -0500 Subject: [PATCH] Allow setting required via boolean attribute per #571 --- src/Former/Traits/Field.php | 17 +++++++++++++++++ tests/LiveValidationTest.php | 27 +++++++++++++++++++++++++++ 2 files changed, 44 insertions(+) diff --git a/src/Former/Traits/Field.php b/src/Former/Traits/Field.php index f0addbd1..30c951c0 100644 --- a/src/Former/Traits/Field.php +++ b/src/Former/Traits/Field.php @@ -190,6 +190,23 @@ public function isRequired() return isset($this->attributes['required']); } + /** + * Set required live validation attribute + * + * @param boolean $isRequired + * @return $this + */ + public function required($isRequired=true) + { + if ($isRequired) { + $this->attributes['required'] = true; + } else { + unset($this->attributes['required']); + } + + return $this; + } + /** * Check if a field is unwrappable (no label) * diff --git a/tests/LiveValidationTest.php b/tests/LiveValidationTest.php index 6e889831..31fec09a 100644 --- a/tests/LiveValidationTest.php +++ b/tests/LiveValidationTest.php @@ -109,6 +109,33 @@ public function testCanSetFieldAsRequired() $this->assertHTML($this->matchControlGroup(), $input); } + public function testCanSetFieldAsRequiredUsingMethod() + { + $input = $this->former->text('foo')->required()->__toString(); + + $this->assertHTML($this->matchField(array('required' => null)), $input); + $this->assertLabel($input, 'foo', true); + $this->assertHTML($this->matchControlGroup(), $input); + } + + public function testMatchFieldWithoutRequired() + { + $input = $this->former->text('foo')->__toString(); + + $this->assertHTML($this->matchField([]), $input); + $this->assertLabel($input, 'foo', false); + $this->assertHTML($this->matchControlGroup(), $input); + } + + public function testCanSetFieldAsNotRequired() + { + $input = $this->former->text('foo')->required()->required(false)->__toString(); + + $this->assertHTML($this->matchField([]), $input); + $this->assertLabel($input, 'foo', false); + $this->assertHTML($this->matchControlGroup(), $input); + } + public function testCanSetNestedBracketFieldAsRequired() { $this->former->withRules(array('foo[bar]' => 'required'));