r/PHPhelp • • Jan 10 '17

Best method for validating a date?

I have a form that will submit dates as "yyyy-mm-dd" if the user uses the date picker, but if they go ahead and enter their date manually, I need to catch this (I think).

I'm stuck with this hacked together function:

http://pastebin.com/iGY043Fs

It works. But I'm just questioning it a little.

The date is destined for a MySQL TIMESTAMP field, so I could just pass the data to that without validating, but I want to give the user a readable error if they're putting in something that won't work.

Thoughts?

8 Upvotes

29 comments sorted by

2

u/colshrapnel Jan 10 '17
function validateDate($string)
{
    $arr=explode("-", $string);
    return count($arr) == 3 && checkdate($arr[1],$arr[2],$arr[0]);
}

2

u/the_alias_of_andrea Jan 10 '17

This would accept technically correct, but weird, dates like 02012-1- 013.

But that's fine, probably, because you can just normalise it (to 2012-01-13).

1

u/[deleted] Jan 10 '17

Interesting.

I just test my date validations by entering a few things:

2017-01-10 (obviously)!
2016-02-29
2017-02-29
ABC

It should go pass, pass, fail, fail.

I hadn't considered that sort of weirdness, honestly.

How much validation is too much? Is that even a proper question?

1

u/lostburner Jan 11 '17

Checking for correct leap days is not too much validation, but it's a good example of why you shouldn't try rolling your own.

1

u/[deleted] Jan 11 '17

Can you elaborate? What other things should I look for? Or just use another library is always the answer?

1

u/lostburner Jan 11 '17

Dates just get more complicated than it's worth, in my opinion. You have edge cases for each month, one every 4 years, one every 100 years, and then another one every 400 years. That's not counting calendar system changes from hundreds of years back. Of course it's up to you where you want to draw the line on the validation trade-off: the hassle of really thorough validation vs. the risk of collecting garbage data.

I'll defer to the many suggestions already in this thread for specific libraries though, since my experience is limited. Personally I'd start by evaluating Carbon, because of its ubiquity.

Here are some edge cases about time handling (though dates are of course simpler): http://infiniteundo.com/post/25326999628/falsehoods-programmers-believe-about-time

1

u/[deleted] Jan 11 '17

Very interesting...

A couple of points:

In this particular instance, I'm just recording a start date and an end date. So, we're not digging deep into the past or future, and just relying on the the assumption that PHP's date functions recognize which dates are valid or not (i.e. not accepting a leap year date on a non leap year). I'm not trying to take a raw string and validate it all on my own, though.

1

u/the_alias_of_andrea Jan 11 '17

relying on the the assumption that PHP's date functions recognize which dates are valid or not

Presumably due to misbehaved other software, PHP's date functions often accept invalid dates and try to find the nearest correct date, IIRC.

1

u/lostburner Jan 11 '17

Date validation should really be designed to reject that input. If a user typed 013 then they've likely made some typo, and you can't be at all sure that they meant 13.

1

u/[deleted] Jan 10 '17

Thank you!

I'd exploded the array originally, but it was spitting out errors if there weren't enough offsets within the array, which was why I ended up with $dd = 0 etc followed by

if(@$arr[0]) { $yy = $arr[0]; }

statements to surpress errors...

Much simpler Thank you!

1

u/headzoo Jan 17 '17

What a horrible way to validate a date. It doesn't even bother to check that $string is formatted using "YYYY-MM-DD". So much can go wrong using this method, especially since the value is coming from a form.

Don't bother answering questions if you don't know what you're doing. Stay away from validation if you don't know what you're doing.

1

u/colshrapnel Jan 17 '17

You must be fun at parties :)

Honestly all your explanations are excellent save for catching a root Exception which is horrible. Either tell him to create and catch specific exception or let him go

1

u/headzoo Jan 17 '17

Alright, alright. I may have jumped the gun on the Exception example.

1

u/Mike312 Jan 10 '17 edited Jan 10 '17

Disregard this, the other guy posted the right answer for what you're doing.

1

u/[deleted] Jan 10 '17

Hmm... I'm not sure about that, it even returns "ABC" as a valid date! :)

1

u/Mike312 Jan 10 '17

Oh, nevermind that, it forces the date to be valid, you're right. I'm almost back at a desktop, I'll edit it

1

u/[deleted] Jan 10 '17

Col Shrapnel gave a great answer that solved it, no worries but thank you!

1

u/omniuni Jan 11 '17

I actually usually do validation in JS and then run it through strtotime, which is pretty amazing. Even if the JS fails, PHP figures it out most of the time, and at least I know it's a valid date of some sort. Also, a recommendation: always store your dates as a Unix timestamp. It's short, simple, time zone neutral, and every single language can work with then easily.

1

u/[deleted] Jan 11 '17

I'm using a JS date picker already. If they stick to that, then all should be good (I assume). So this is for the even that they avoid using that, which could be either for input speed (which would still be able to be validated in JS) or if JavaScript happened to be disabled (which would kill the date picker and the validation mechanism as well).

I also looked at unix timestamps, and maybe I'll switch that that in the future. I'm probably just lazy, but it seems like it takes extra manipulation to render the date in a readable format, whether through PHP or browsing the database directly.

1

u/[deleted] Jan 11 '17

Thoughts?

You can't reliably validate a random string into a date. There are just to many weird ways to note them. I wouldn't use an input field for the date but the date picker showing the date in a div only. Or add three input fields telling the user what to input where.

Unfortunately type="date" is only supported by modern browsers.

1

u/[deleted] Jan 11 '17

I'm using a input field with a placeholder that's shows what the expected input is, along with a pop up date picker. Reason is, for me I HATE being made to use the mouse unnecessarily. So I just want a method to reject invalid inputs if the user opts for keyboard entry, and give them a human readable error.

3

u/notian Jan 10 '17

The simplest solution is to use strtotime and check that the return isn't false.

You could also do a new DateTime in a try/catch block and respond with an error if it throws an exception.

public function getValidDate($string){
	try{ 
		$date = new DateTime( $string );
	}catch( Exception $e ){
		return false;
	}
	/* Do some more date validation on the object */
	return $date->format( 'Y-m-d' );;
}

public function getValidDate($string){
	if(false !== ($date = strtotime( $string )){
		return date('Y-m-d', $date );
	}
	return false;
}

2

u/the_alias_of_andrea Jan 10 '17

strtotime is quite loose and accepts a lot of date formats. I think that could go wrong here, if guesses the order of the fields wrong.

It'd be better to validate against the specific date format being used here.

2

u/notian Jan 10 '17

The fact that it is loose is an up-side to me. If the user enters mm/dd/yyyy or yyyy/mm/dd then it will be accepted and understood, and only in a small number of cases result in flipped month/day values (i.e. when the day <12 it becomes less predictable).

1

u/the_alias_of_andrea Jan 11 '17

The user won't necessarily know if that happened, though.

2

u/lchoate Jan 10 '17

If you can pull in another library, look into carbon/carbon. It is a life saver.

1

u/holyshock Jan 10 '17 edited Jan 10 '17

Always validate data, even if you're sure the user will always use datepicker. If you are sure user will always submit with YYYY-MM-DD format, then something like this is the best approach...

 $userSubmittedDate = "2017-01-01";
 if (date("Y-m-d", strtotime($userSubmittedDate)) !== $userSubmittedDate) {
   //problem...
 } else {
  // fine!
 }

1

u/preinheimer Jan 11 '17

So I use a multi-step approach, demo: http://recordit.co/GvoFm6bDRq

  • I send the contents of my date field using ajax to the server, which runs strtotime on it, and returns the date in a common format

  • I update the text field to YYYY-MM-DD from that dat

  • I display that date underneath in a more human readable format under the text box.

I like this approach because strtotime can be confused (some dates are ambiguous), and this way the user sees what they're getting.