Skip to content

Commit ebe1d00

Browse files
committed
Add rule Name
1 parent 6935a4e commit ebe1d00

File tree

2 files changed

+77
-0
lines changed

2 files changed

+77
-0
lines changed

resources/lang/en/validation.php

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
'float_number' => 'The :attribute must be a float number.',
1414
'hash' => 'The :attribute must be a hash of :algorithm algorithm.',
1515
'image_url' => 'The :attribute must be a valid image URL.',
16+
'name' => 'The :attribute must be a valid name.',
1617
'phone' => 'The :attribute must be a valid phone number.',
1718
'username' => 'The :attribute must be a valid username.',
1819
'without_spaces' => 'The :attribute must not contain spaces.',

src/Rules/Name.php

Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
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 name.
9+
*
10+
* - at least one letter (a-z, A-Z)
11+
* - no emoji
12+
* - no number (if $allowNumber flag is false)
13+
*
14+
* @package Arifszn\AdvancedValidation\Rules
15+
*/
16+
class Name implements Rule
17+
{
18+
/**
19+
* @var bool
20+
*/
21+
private $allowNumber;
22+
23+
/**
24+
* @var string
25+
*/
26+
private $errorMessage;
27+
28+
/**
29+
* Create a new rule instance.
30+
*
31+
* @param bool $allowNumber Allow number.
32+
* @param string|null $errorMessage Custom error message.
33+
* @return void
34+
*/
35+
public function __construct(bool $allowNumber = false, string $errorMessage = null)
36+
{
37+
$this->allowNumber = $allowNumber;
38+
$this->errorMessage = $errorMessage;
39+
}
40+
41+
/**
42+
* Determine if the validation rule passes.
43+
*
44+
* @param string $attribute
45+
* @param mixed $value
46+
* @return bool
47+
*/
48+
public function passes($attribute, $value)
49+
{
50+
// check at least one letter (a-z, A-Z)
51+
if (!preg_match('/[A-Za-z]+/', $value)) {
52+
return false;
53+
}
54+
55+
// check no emoji
56+
if (preg_match('/\p{S}/u', $value)) {
57+
return false;
58+
}
59+
60+
if ($this->allowNumber && !preg_match('/^([^0-9]*)$/', $value)) {
61+
return false;
62+
}
63+
64+
return true;
65+
}
66+
67+
/**
68+
* Get the validation error message.
69+
*
70+
* @return string
71+
*/
72+
public function message()
73+
{
74+
return $this->errorMessage ? $this->errorMessage : trans('advancedValidation::validation.name');
75+
}
76+
}

0 commit comments

Comments
 (0)