Skip to content

Commit 70bf6e5

Browse files
committed
Allow to set validation failed message in the custom validator
1 parent 422d5e9 commit 70bf6e5

File tree

3 files changed

+24
-5
lines changed

3 files changed

+24
-5
lines changed

src/Input/InputIO.php

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -217,10 +217,7 @@ private function drawInputWithError(Input $input, string $userInput) : void
217217
$this->drawCenteredLine(
218218
$input,
219219
$userInput,
220-
sprintf(
221-
'%s',
222-
$input->getValidationFailedText()
223-
)
220+
$input->getValidationFailedText()
224221
);
225222
$this->drawEmptyLine($input, $userInput);
226223
}

src/Input/Password.php

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -81,7 +81,7 @@ public function getPlaceholderText() : string
8181
return $this->placeholderText;
8282
}
8383

84-
public function setValidator(callable $validator)
84+
public function setValidator(callable $validator) : void
8585
{
8686
$this->validator = $validator;
8787
}
@@ -95,6 +95,11 @@ public function validate(string $input) : bool
9595
{
9696
if ($this->validator) {
9797
$validator = $this->validator;
98+
99+
if ($validator instanceof \Closure) {
100+
$validator = $validator->bindTo($this);
101+
}
102+
98103
return $validator($input);
99104
}
100105

test/Input/PasswordTest.php

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -119,4 +119,21 @@ public function customValidateProvider() : array
119119
['999ppp', true],
120120
];
121121
}
122+
123+
public function testWithCustomValidatorAndCustomValidationMessage() : void
124+
{
125+
$customValidate = function ($input) {
126+
if ($input === 'mypassword') {
127+
$this->setValidationFailedText('Password too generic');
128+
return false;
129+
}
130+
return true;
131+
};
132+
133+
$this->input->setValidator($customValidate);
134+
135+
self::assertTrue($this->input->validate('superstrongpassword'));
136+
self::assertFalse($this->input->validate('mypassword'));
137+
self::assertEquals('Password too generic', $this->input->getValidationFailedText());
138+
}
122139
}

0 commit comments

Comments
 (0)