Last active
April 30, 2017 09:01
-
-
Save kenan-recebli/f1123939aa97cdfbeaf2586099dff705 to your computer and use it in GitHub Desktop.
Day, month and year validation rules for Laravel 5.4
This file contains hidden or 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 | |
namespace App\Http\Requests; | |
class Validator | |
{ | |
/** | |
* Validate that an attribute is a valid day. | |
* | |
* @param string $attribute | |
* @param int $day | |
* | |
* @return bool | |
*/ | |
public function validateDay($attribute, $day) | |
{ | |
return is_numeric($day) && $day > 0 && $day < 32; | |
} | |
/** | |
* Validate that an attribute is month. | |
* | |
* @param string $attribute | |
* @param int $month | |
* @param array $parameters | |
* @param \Illuminate\Support\Facades\Validator $validator | |
* | |
* @return bool | |
*/ | |
public function validateMonth($attribute, $month, $parameters, $validator) | |
{ | |
$day = $validator->getData()[$parameters[0]]; | |
if (! $day or ! is_numeric($month) or $month < 1 or $month > 12) { | |
return false; | |
} | |
switch ($month) { | |
case 2: | |
return $day < 30; | |
case 4: | |
case 6: | |
case 9: | |
case 11: | |
return $day < 31; | |
default: | |
return $day < 32; | |
} | |
} | |
/** | |
* Validate that an attribute is a valid year. | |
* | |
* | |
* @param string $attribute | |
* @param int $year | |
* @param array $parameters | |
* @param \Illuminate\Support\Facades\Validator $validator | |
* | |
* @return bool | |
*/ | |
public function validateYear($attribute, $year, $parameters, $validator) | |
{ | |
if (! is_numeric($year) or $year < 1910 or $year > date('Y') - 3) { | |
return false; | |
} | |
$data = $validator->getData(); | |
if (! $day = $data[$parameters[0]] or ! $month = $data[$parameters[1]]) { | |
return false; | |
} | |
return ! ($year % 4 && $month == 2 && $day == 29); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment