|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace App\Rules; |
| 4 | + |
| 5 | +use Closure; |
| 6 | +use Illuminate\Contracts\Validation\ValidationRule; |
| 7 | + |
| 8 | +class ValidUsername implements ValidationRule |
| 9 | +{ |
| 10 | + /** |
| 11 | + * Run the validation rule. |
| 12 | + * |
| 13 | + * @param \Closure(string, ?string=): \Illuminate\Translation\PotentiallyTranslatedString $fail |
| 14 | + */ |
| 15 | + public function validate(string $attribute, mixed $value, Closure $fail): void |
| 16 | + { |
| 17 | + if (! preg_match('/^[a-zA-Z0-9_.-]+$/', $value)) { |
| 18 | + $fail('The :attribute can only contain letters, numbers, underscores, hyphens, and periods.'); |
| 19 | + |
| 20 | + return; |
| 21 | + } |
| 22 | + |
| 23 | + if (str_starts_with($value, '.')) { |
| 24 | + $fail('The :attribute cannot start with a period.'); |
| 25 | + |
| 26 | + return; |
| 27 | + } |
| 28 | + |
| 29 | + if (str_starts_with($value, '_')) { |
| 30 | + $fail('The :attribute cannot start with an underscore.'); |
| 31 | + |
| 32 | + return; |
| 33 | + } |
| 34 | + |
| 35 | + if (str_starts_with($value, '-')) { |
| 36 | + $fail('The :attribute cannot start with a hyphen.'); |
| 37 | + |
| 38 | + return; |
| 39 | + } |
| 40 | + |
| 41 | + if (str_ends_with($value, '.')) { |
| 42 | + $fail('The :attribute cannot end with a period.'); |
| 43 | + |
| 44 | + return; |
| 45 | + } |
| 46 | + |
| 47 | + if (str_ends_with($value, '-')) { |
| 48 | + $fail('The :attribute cannot end with a hyphen.'); |
| 49 | + |
| 50 | + return; |
| 51 | + } |
| 52 | + |
| 53 | + if (str_contains($value, '--')) { |
| 54 | + $fail('The :attribute cannot contain consecutive hyphens.'); |
| 55 | + |
| 56 | + return; |
| 57 | + } |
| 58 | + |
| 59 | + if (str_contains($value, '..')) { |
| 60 | + $fail('The :attribute cannot contain consecutive periods.'); |
| 61 | + |
| 62 | + return; |
| 63 | + } |
| 64 | + } |
| 65 | +} |
0 commit comments