Last active
September 27, 2023 23:40
-
-
Save xxRockOnxx/c3a724a6ada1c3386268eba1c443c37b to your computer and use it in GitHub Desktop.
[Laravel] Custom Validation rule for day of week.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
Validator::extend('day', function($attribute, $value, $parameters, $validator) { | |
// Laravel uses Carbon. Just `use Carbon\Carbon;` it | |
$day = Carbon::parse($value)->dayOfWeek; | |
switch (strtolower($parameters[0])) { | |
case 'sunday': | |
return $day == 0; | |
case 'monday': | |
return $day == 1; | |
case 'tuesday': | |
return $day == 2; | |
case 'wednesday': | |
return $day == 3; | |
case 'thursday': | |
return $day == 4; | |
case 'friday': | |
return $day == 5; | |
case 'saturday': | |
return $day == 6; | |
default: | |
return false; | |
} | |
}); | |
Validator::replacer('day', function($message, $attribute, $rule, $parameters){ | |
return str_replace(':day', $parameters[0], $message); | |
}); | |
/* | |
* Sample error message | |
* 'registration_date.day' => ':attribute must fall on :day' | |
*/ | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment