Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

miteshjain's avatar

How to validate a date from excel import?

I had used Maatwebsite LARAVEL EXCEL, while importing, I want to validate the DOB ? I am using carbon instance, but how to validate a date?

0 likes
3 replies
bobbybouwmann's avatar

Did you read the documentation, they have this example there.

try { 
    Carbon::create(1975, 5, 21, 22, -2, 0); 
} catch(InvalidArgumentException $x) { 
    echo $x->getMessage(); 
}

Another example from the documentation

Carbon::createFromFormat($format, $time, $tz);

createFromFormat() is mostly a wrapper for the base php function DateTime::createFromFormat. The difference being again the $tz argument can be a DateTimeZone instance or a string timezone value. Also, if there are errors with the format this function will call the `` DateTime::getLastErrors()method and then throw aInvalidArgumentExceptionwith the errors as the message. If you look at the source for thecreateXX()functions above, they all make a call tocreateFromFormat()`.

Source: http://carbon.nesbot.com/docs/

So you need to create a date using the createXX method and then you can catch the exception if something is wrong with the data

Here is a small example

// Let's say the data you expect has this format Y-m-d
// So an example date could look like this 2015-11-05
// Now when you do this it should work
try {
    $date = Carbon::createFromFormat('Y-m-d', '2015-11-05')
} catch(InvalidArgumentException $x) { 
    echo $x->getMessage(); 
}

// Now this "2015-3-3 12:23:00" won't work because the format doesn't match
try {
    $date = Carbon::createFromFormat('Y-m-d', '2015-3-3 12:23:00')
} catch(InvalidArgumentException $x) { 
    echo $x->getMessage(); 
}

// I'm not sure if this "2015-23-10" will fail
// So the month is invalid
// This is your homework for the weekend ;)
// I think it will spit out 2016-11-10, but I'm not sure about it :P
try {
    $date = Carbon::createFromFormat('Y-m-d', '2015-23-10')
} catch(InvalidArgumentException $x) { 
    echo $x->getMessage(); 
}
miteshjain's avatar

I had already seen those examples, but what I meant from excel import is, the format for DOB in excel might not be DD/MM/YYYY all the time. If for example, there is DD/MM/YY OR D/M/YYYY then how to validate this as true date. I was looking for such validation.

Thanks

davidfaux's avatar

if strtotime() can parse it it is a valid date however if it is the correct date is another story ;)

Please or to participate in this conversation.