Skip to content

Commit adf8d6d

Browse files
author
Ariful Alam
committed
Add rule username
1 parent a60034d commit adf8d6d

File tree

2 files changed

+57
-0
lines changed

2 files changed

+57
-0
lines changed

resources/lang/en/validation.php

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,5 +14,6 @@
1414
'float_number' => 'The :attribute must be a float number',
1515
'image_url' => 'The :attribute must be a valid image URL.',
1616
'phone' => 'The :attribute must be a valid phone number.',
17+
'username' => 'The :attribute must be a valid username.',
1718
'without_spaces' => 'The :attribute must not contain spaces.',
1819
];

src/Rules/Username.php

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
<?php
2+
3+
namespace Arifszn\AdvancedValidation\Rules;
4+
5+
use Illuminate\Contracts\Validation\Rule;
6+
7+
/**
8+
* The field under validation must be a valid username.
9+
*
10+
* - starts with a letter (alpha)
11+
* - only alpha-numeric (a-z, A-Z, 0-9), underscore, minus and dot
12+
* - multiple underscores, minus and are not allowed (-- or __ or ..)
13+
* - underscores, minus and dot are not allowed at the beginning or end
14+
*
15+
* @package Arifszn\AdvancedValidation\Rules
16+
*/
17+
class Username implements Rule
18+
{
19+
/**
20+
* @var string
21+
*/
22+
private $errorMessage;
23+
24+
/**
25+
* Create a new rule instance.
26+
*
27+
* @param string|null $errorMessage Custom error message.
28+
* @return void
29+
*/
30+
public function __construct(string $errorMessage = null)
31+
{
32+
$this->errorMessage = $errorMessage;
33+
}
34+
35+
/**
36+
* Determine if the validation rule passes.
37+
*
38+
* @param string $attribute
39+
* @param mixed $value
40+
* @return bool
41+
*/
42+
public function passes($attribute, $value)
43+
{
44+
return preg_match('/^[a-z][a-z0-9]*(?:[_\-\.][a-z0-9]+)*$/i', $value);
45+
}
46+
47+
/**
48+
* Get the validation error message.
49+
*
50+
* @return string
51+
*/
52+
public function message()
53+
{
54+
return $this->errorMessage ? $this->errorMessage : trans('advancedValidation::validation.username');
55+
}
56+
}

0 commit comments

Comments
 (0)