Skip to content

Commit

Permalink
Fix username validation bug
Browse files Browse the repository at this point in the history
  • Loading branch information
lcharette committed Feb 16, 2024
1 parent 467e29f commit 4178f9c
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 1 deletion.
2 changes: 1 addition & 1 deletion src/Fortress/Validator/CustomValidatorRules.php
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,6 @@ public static function validatePhoneUS(string $field, mixed $value): bool
*/
public static function validateUsername(string $field, mixed $value): bool
{
return preg_match('/^([a-z0-9\.\-_])+$/i', $value) === 1;
return preg_match('/^([a-z0-9\.\-_])+$/i', strval($value)) === 1;
}
}
30 changes: 30 additions & 0 deletions tests/Fortress/Validator/ServerSideValidatorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -814,6 +814,9 @@ public function testValidateUsername(): void
'user_name' => '',
]));

// Check with missing data
$this->assertEmpty($this->validator->validate($schema, []));

// Check failing validations - Code not allowed
$errors = $this->validator->validate($schema, [
'user_name' => "<script>alert('I got you');</script>",
Expand All @@ -836,6 +839,33 @@ public function testValidateUsername(): void
$this->assertSame(["Sorry buddy, that's not a valid username."], $errors['user_name']);
}

/**
* Test specific bug: When required validator rule is defined, username
* validator is still called, even if there's no data. This is not the case
* without "required". In this case, `validateUsername` should be ignored,
* or accept a null value.
*/
public function testValidateUsernameForMissingData(): void
{
// Arrange
$schema = new RequestSchema([
'user_name' => [
'validators' => [
'required' => [
'message' => 'Username required',
],
'username' => [
'message' => "Sorry buddy, that's not a valid username.",
],
],
],
]);

$errors = $this->validator->validate($schema, []);
$this->assertNotEmpty($errors);
$this->assertSame(['Username required', "Sorry buddy, that's not a valid username."], $errors['user_name']);
}

public function testDomainRulesClientOnly(): void
{
// Arrange
Expand Down

0 comments on commit 4178f9c

Please sign in to comment.