diff --git a/src/Fortress/Validator/CustomValidatorRules.php b/src/Fortress/Validator/CustomValidatorRules.php index a13276b..699f839 100644 --- a/src/Fortress/Validator/CustomValidatorRules.php +++ b/src/Fortress/Validator/CustomValidatorRules.php @@ -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; } } diff --git a/tests/Fortress/Validator/ServerSideValidatorTest.php b/tests/Fortress/Validator/ServerSideValidatorTest.php index d28e662..758de6f 100644 --- a/tests/Fortress/Validator/ServerSideValidatorTest.php +++ b/tests/Fortress/Validator/ServerSideValidatorTest.php @@ -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' => "", @@ -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