问题
Hello i'm writing a custom validation for input data in my laravel project. I'm using Carbon::createFromDate()->age in order to get user age and check whether he's 16 or more. I reckon i'm not doing it properly because i get InvalidArgumentException with such errors:
$rok is a year(1996 eg.) $miesiac is a month and $dzien is a Day. Pesel is an unique ID number of a Polish citizen. From pesel i get the date(year, month, day)
I'm getting some big numbers and i don't know what they mean Here's dd: "year:21586738427 month:1900167 day:9001727"
Here's code of my AppServiceProvider
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use Carbon\Carbon;
use Validator;
use Log;
class AppServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
//Custom validator for pesel validation
Validator::extend('pesel',function($attribute,$value,$parameters)
{
$v = $value;
//check if psesel is 11 chars long
if (strlen($v) != 11)
{
Log::info("Pesel is not 11 chars long");
return;
}
//check whether all chars are numbers
$aInt = array();
for($i = 0; $i < 11; $i++)
{
$val = substr($v,$i+1);
$valInt = (int) $val;
$aInt[$i] = $valInt;
if(is_nan($aInt[$i]))
{
Log::info("User inserted invalid number");
return;
}
}
//check control sum
$wagi = [1,3,7,9,1,3,7,9,1,3,1];
$sum = 0;
for($i = 0;$i < 11;$i++)
{
$sum += $wagi[$i]*$aInt[$i];
if(Log::info(($sum%10)!=0))
{
return;
}
//count the year,month,and day from pesel
$rok = 1900+$aInt[0]*10+$aInt[1];
if($aInt[2]>=2 && $aInt[2]<8)
{
$rok += floor($aInt[2]/2)*100;
}
if($aInt[2]>=8)
{
$rok -= 100;
}
$miesiac = ($aInt[2]%2)*10+$aInt[3];
$dzien = $aInt[4]*10+$aInt[5];
Log::info("Parsing the date in carbon");
//validate whether user is 16 years or more
$userAge = Carbon::createFromDate($rok, $miesiac, $dzien,'Europe/Warsaw')->age;
if($userAge < 16)
{
Log::info("user is not 16 or more");
return;
}
}
});
}
/**
* Register any application services.
*
* @return void
*/
public function register()
{
//
}
}
回答1:
Ok i solved the problem. It was fault of my code
$val = substr($v,$i+1);
is wrong it should be
$val = substr($v,$i,1);
Now it works
来源:https://stackoverflow.com/questions/41086913/invalidargumentexception-in-carboncreatefromdate-age