Skip to content

Commit

Permalink
Improve validation message when handle starts with a number
Browse files Browse the repository at this point in the history
  • Loading branch information
duncanmcclean committed Feb 27, 2025
1 parent 80c0b89 commit 54f1f9b
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 0 deletions.
1 change: 1 addition & 0 deletions resources/lang/en/validation.php
Original file line number Diff line number Diff line change
Expand Up @@ -156,6 +156,7 @@

'arr_fieldtype' => 'This is invalid.',
'handle' => 'Must contain only lowercase letters and numbers with underscores as separators.',
'handle_starts_with_number' => 'Cannot start with a number.',
'slug' => 'Must contain only letters and numbers with dashes or underscores as separators.',
'code_fieldtype_rulers' => 'This is invalid.',
'composer_package' => 'Must be a valid composer package name (eg. hasselhoff/kung-fury).',
Expand Down
5 changes: 5 additions & 0 deletions src/Rules/Handle.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,16 @@

use Closure;
use Illuminate\Contracts\Validation\ValidationRule;
use Illuminate\Support\Str;

class Handle implements ValidationRule
{
public function validate(string $attribute, mixed $value, Closure $fail): void
{
if (Str::startsWith($value, range(0, 9))) {
$fail('statamic::validation.handle_starts_with_number')->translate();
}

if (! preg_match('/^[a-zA-Z][a-zA-Z0-9]*(?:_{0,1}[a-zA-Z0-9])*$/', $value)) {
$fail('statamic::validation.handle')->translate();
}
Expand Down
6 changes: 6 additions & 0 deletions tests/Rules/HandleTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -43,4 +43,10 @@ public function it_outputs_helpful_validation_error()
{
$this->assertValidationErrorOutput(trans('statamic::validation.handle'), '_bad_input');
}

#[Test]
public function it_outputs_helpful_validation_error_when_string_starts_with_number()
{
$this->assertValidationErrorOutput(trans('statamic::validation.handle_starts_with_number'), '1bad_input');
}
}

0 comments on commit 54f1f9b

Please sign in to comment.