Re: Date validation

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



On 20/05/11 16:29, Geoff Lane wrote:
On Friday, May 20, 2011, Peter Lind wrote:

Try:

$date = new DateTime($date_string_to_validate);
echo $date->format('Y-m-d');

Many thanks. Unfortunately, as I mentioned in my OP, the DateTime
class seems to be 'broken' for my purposes because it uses strtotime()
to convert input strings to date/time. Rather than fail when presented
with an invalid date, strtotime() returns the 'best fit' if possible.
This can be seen from:

$date = new DateTime('30 Feb 1999');
echo $date->format('Y-m-d');

which results in "1999-03-02" even though 30 Feb is an invalid date.


If you could programmatically determine the format of the input, you could parse the date using DateTime and then rewrite it using the same format as the input, and compare those. Now that starts to work if you can *control* the format of the input, or at least limit it to some familiar options.

So maybe:

$userInput = '30 Feb 1999';
$dateTest = new DateTime($userInput);
if ($userInput===$dateTest->format('Y-m-d') ||
    $userInput===$dateTest->format('d M Y'))
{
	echo 'Date is valid';
}
else
{
	echo 'Not valid';
}

It starts to get logn-winded after a while, and doesn't rule out ambiguous cases...
Or split the date input into pieces in the form (if possible) and then you can validate the date how you like

$userInput = $_POST['year'].'-'.$_POST['month'].'-'.$_POST['day'];
$dateTest = new DateTime($userInput);
if ($userInput===$dateTest->format('Y-m-d'))
{
	echo 'Date is valid';
}
else
{
	echo 'Not valid';
}


Finally, for some applications I have made an AJAX (javascript + PHP) implementation which provides feedback to the user as they type in the date field: every time a character is typed in the box, the backend is asked to parse it and then format it in an unambiguous way and send it back to the client. That way the user can *see* if what they are typing is valid... Of course, you *still* have to validate it when it's posted (and the network overhead might be too much).



--
Peter Ford, Developer                 phone: 01580 893333 fax: 01580 893399
Justcroft International Ltd.                              www.justcroft.com
Justcroft House, High Street, Staplehurst, Kent   TN12 0AH   United Kingdom
Registered in England and Wales: 2297906
Registered office: Stag Gates House, 63/64 The Avenue, Southampton SO17 1XS

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux