Skip to content

Instantly share code, notes, and snippets.

@xxRockOnxx
Last active September 27, 2023 23:40
Show Gist options
  • Save xxRockOnxx/c3a724a6ada1c3386268eba1c443c37b to your computer and use it in GitHub Desktop.
Save xxRockOnxx/c3a724a6ada1c3386268eba1c443c37b to your computer and use it in GitHub Desktop.
[Laravel] Custom Validation rule for day of week.
<?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