[PHP] Re: Date validation

2011-05-23 Thread Pete Ford

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 89 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



[PHP] Re: Date validation

2011-05-23 Thread tedd

At 9:47 AM +0100 5/23/11, Pete Ford wrote:
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).


That would be interesting to see.

With a little work, I envision a way to alleviate the Europe/US date 
format difference. (i.e., day/month/year : Europe vs month/day/year : 
US).


As the user typed in the date, the day/month problem could be shown 
via string-month (i.e., Jan... ).


How does yours work?

Cheers,

tedd

--
---
http://sperling.com/

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



Re: [PHP] Re: Date validation

2011-05-23 Thread Pete Ford

On 23/05/11 13:12, tedd wrote:

At 9:47 AM +0100 5/23/11, Pete Ford wrote:

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).


That would be interesting to see.

With a little work, I envision a way to alleviate the Europe/US date
format difference. (i.e., day/month/year : Europe vs month/day/year : US).

As the user typed in the date, the day/month problem could be shown via
string-month (i.e., Jan... ).

How does yours work?

Cheers,

tedd


Ah, now you're asking.
I'll have to try and extract the code into a sanitised form for public 
consumption: give me a little time...
But yes, the string fed back to the user gives the month as a string, to avoid 
confusion with numeric months.


--
Peter Ford, Developer phone: 01580 89 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



Re: [PHP] Re: Date validation

2011-05-23 Thread Tamara Temple

Isn't this typically why date selectors are used on the front end?

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



Re: [PHP] Re: Date validation

2011-05-23 Thread Andrew Ballard
On Mon, May 23, 2011 at 9:55 AM, Tamara Temple tamouse.li...@gmail.com wrote:
 Isn't this typically why date selectors are used on the front end?


Not really. Date selectors are intended to make data entry easier on
the front end while allowing only valid date selections, but you can't
really rely on them.

* Most date selectors rely on Javascript, which may not be available
on the client.

* From a usability perspective, using a date selector is slower than
typing the date into a text field. Accessibility is also a concern.

* Above all, your code should still validate the correctness of input
on the server regardless of anything you are doing to make things
easier in the client. There are ways around using date selectors.

Andrew

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



[PHP] Re: Date validation

2011-05-21 Thread Geoff Lane
I'm posting here for completeness as I've now rolled my own date
validator (code follows my sig). It allows almost all valid 'English'
formats except ordinal day values (1st, 3rd, etc.) Because I'm in UK
and writing for a UK audience, I've parsed ambiguous dates as d/m/y.
Those writing for places where m/d/y is the convention will probably
want to alter the tests in the second if ... elseif construct. It's a
bit long-winded, but by all means use or modify if it's any use to
you.

Best regards,

Geoff

---8--

function is_date ($str){
$dateOK = TRUE;
if (stristr($str, /)){
$aryDate = explode (/, $str);
} elseif (stristr($str, -)){
$aryDate = explode (-, $str);
} elseif (stristr($str,  )){
$aryDate = explode ( , $str);
} else {
$dateOK = FALSE;
}
if (count($aryDate) != 3){
// we don't have the correct number of date parts
$dateOK = FALSE;
}
if ($dateOK) {
// trim any leading or trailing whitespace
for ($i = 0; $i  count($aryDate); $i++){
$aryDate[$i] = trim($aryDate[$i]);
}
// determine which value is month and which is day
if (!is_numeric($aryDate[0])){
$month = $aryDate[0];
$day = $aryDate[1];
} elseif (!is_numeric($aryDate[1])){
$day = $aryDate[0];
$month = $aryDate[1];
} elseif ($aryDate[1] = 12){
$day = $aryDate[0];
$month = $aryDate[1];
} else {
$month = $aryDate[0];
$day = $aryDate[1];
}
$year = $aryDate[2];
// Expand 2-digit years to 4 digits. Cut-off is current year + 10.
if (strlen($year) != 4){
$now = date('y') + 10;
$year = $year - $now  0 ? '20' . $year : '19' . $year;
// check for correct year length
if (strlen($year) != 4){
// we didn't start with two digits
$dateOK = FALSE;
}
}
// Convert month names to month numbers
if (!is_numeric($month)){
$aryMonth = array('nowt', 'jan', 'feb', 'mar', 'apr', 'may', 'jun', 
'jul', 'aug', 'sep', 'oct', 'nov', 'dec');
$month = strtolower(substr($month, 0, 3));
foreach ($aryMonth AS $key = $value){
if ($value == $month){
$month = $key;
}
}
}
$dateOK = $dateOK  checkdate($month, $day, $year);
}
return ($dateOK);
}


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



[PHP] Re: Date validation

2011-05-20 Thread Jo�o C�ndido de Souza Neto
What about using this:

$date = DateTime::createFromFormat(Y-m-d, 2011-05-20);

-- 
João Cândido de Souza Neto

Geoff Lane ge...@gjctech.co.uk escreveu na mensagem 
news:11565581.20110520132...@gjctech.co.uk...
 Hi All,

 I'm scratching my head trying to remember how I validated string
 representation of dates 'the first time around' with PHP (before going
 over to ASP/VBScript for almost a decade). I have a feeling that I
 must have rolled my own validation function, because I can't find
 anything other than strtotime() and checkdate() in PHP itself.

 Although checkdate() seems fine, strtotime() appears to be 'broken'.
 It seems where possible to return a timestamp that makes some sense
 rather than return FALSE when handed an invalid date. For example,
 strtotime('30 Feb 1999') returns 920332800, which is equivalent to
 strtotime('02 Mar 1999'). When I ask a user to enter a date and they
 make a typo, forget that September only has 30 days, etc., I want to
 be able to detect the problem rather than post a date in the following
 month!

 It also seems that where the DateTime class uses string representation
 of dates, times, or intervals that these must be 'in a format accepted
 by strtotime()'; which implies that 'under the hood' strtotime() is
 used to convert the string to a date/time value, which implies that
 the Date/Time class cannot properly handle string input values.

 This seems to be such a common requirement that I suspect I've missed
 something basic. I'd thus be grateful for any pointers as to how to
 properly validate user-input string representation of dates.

 Cheers,

 -- 
 Geoff Lane
 



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



[PHP] Re: Date validation

2011-05-20 Thread Geoff Lane
 On Friday, May 20, 2011, João Cândido de Souza Neto wrote:

 What about using this:

 $date = DateTime::createFromFormat(Y-m-d, 2011-05-20);

Hi João, and thanks for your help.

FWIW, I thought about that but it didn't work for me. On further
investigation, I'm now completely confused and suspect I've got a duff
PHP installation. Thankfully, it's a virtual machine so it should be
reasonable easy to 'vapourise' and start over (perhaps with CentOS
rather than Ubuntu as the OS).

Anyway, the following code produces the following result when the
variable $str = '7 feb 2010':

[code]
  echo pDate is $str/p\n;
  $date = DateTime::createFromFormat('d M Y', $str);
  echo pre;
  print_r($date);
  echo /pre\n;
  echo date('d M Y') . br / . date('d M Y', $date);
[/code]

[result]
  pDate is 7 feb 2010/p
  preDateTime Object
  (
  [date] = 2010-02-07 15:11:34
  [timezone_type] = 3
  [timezone] = Europe/London
  )
  /pre
  20 May 2011br /
[/result]

This is pretty much as expected except that the second call to date()
- i.e. date('d M Y', $date) - outputs nothing.

Also, AFAICT createFromFormat fails if the date is not formatted
according to the first parameter. So, for example:
  $date = DateTime::createFromFormat('d M Y', '5/2/10')
fails ... (at least, it does on my system :( )

-- 
Geoff


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



Re: [PHP] Re: Date validation

2011-05-20 Thread Peter Lind
On 20 May 2011 16:22, Geoff Lane ge...@gjctech.co.uk wrote:
  On Friday, May 20, 2011, João Cândido de Souza Neto wrote:

 What about using this:

 $date = DateTime::createFromFormat(Y-m-d, 2011-05-20);

 Hi João, and thanks for your help.

 FWIW, I thought about that but it didn't work for me. On further
 investigation, I'm now completely confused and suspect I've got a duff
 PHP installation. Thankfully, it's a virtual machine so it should be
 reasonable easy to 'vapourise' and start over (perhaps with CentOS
 rather than Ubuntu as the OS).

 Anyway, the following code produces the following result when the
 variable $str = '7 feb 2010':

 [code]
  echo pDate is $str/p\n;
  $date = DateTime::createFromFormat('d M Y', $str);
  echo pre;
  print_r($date);
  echo /pre\n;
  echo date('d M Y') . br / . date('d M Y', $date);
 [/code]

 [result]
  pDate is 7 feb 2010/p
  preDateTime Object
  (
      [date] = 2010-02-07 15:11:34
      [timezone_type] = 3
      [timezone] = Europe/London
  )
  /pre
  20 May 2011br /
 [/result]

 This is pretty much as expected except that the second call to date()
 - i.e. date('d M Y', $date) - outputs nothing.

date() takes an int as second parameter - a timestamp. Not an object.
And from a quick test it doesn't look like DateTime has a __toString
method.

 Also, AFAICT createFromFormat fails if the date is not formatted
 according to the first parameter. So, for example:
  $date = DateTime::createFromFormat('d M Y', '5/2/10')
 fails ... (at least, it does on my system :( )


I'm sorry for asking but what did you expect?? You're specifically
calling a method that parses a string according to a given format. If
it parsed the string according to any other format, that would be a
huge WTF.

Regards
Peter

-- 
hype
WWW: plphp.dk / plind.dk
LinkedIn: plind
BeWelcome/Couchsurfing: Fake51
Twitter: kafe15
/hype

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



Re: [PHP] Re: Date validation

2011-05-20 Thread Jo�o C�ndido de Souza Neto
If you look carefully, you´ll notice that I´m using the DateTime object 
(default from PHP 5.2.0 or higher) not the function date.

-- 
João Cândido de Souza Neto

Peter Lind peter.e.l...@gmail.com escreveu na mensagem 
news:banlktinjonyvfnqjqtfqtdmu_r2-cfp...@mail.gmail.com...
On 20 May 2011 16:22, Geoff Lane ge...@gjctech.co.uk wrote:
 On Friday, May 20, 2011, João Cândido de Souza Neto wrote:

 What about using this:

 $date = DateTime::createFromFormat(Y-m-d, 2011-05-20);

 Hi João, and thanks for your help.

 FWIW, I thought about that but it didn't work for me. On further
 investigation, I'm now completely confused and suspect I've got a duff
 PHP installation. Thankfully, it's a virtual machine so it should be
 reasonable easy to 'vapourise' and start over (perhaps with CentOS
 rather than Ubuntu as the OS).

 Anyway, the following code produces the following result when the
 variable $str = '7 feb 2010':

 [code]
 echo pDate is $str/p\n;
 $date = DateTime::createFromFormat('d M Y', $str);
 echo pre;
 print_r($date);
 echo /pre\n;
 echo date('d M Y') . br / . date('d M Y', $date);
 [/code]

 [result]
 pDate is 7 feb 2010/p
 preDateTime Object
 (
 [date] = 2010-02-07 15:11:34
 [timezone_type] = 3
 [timezone] = Europe/London
 )
 /pre
 20 May 2011br /
 [/result]

 This is pretty much as expected except that the second call to date()
 - i.e. date('d M Y', $date) - outputs nothing.

date() takes an int as second parameter - a timestamp. Not an object.
And from a quick test it doesn't look like DateTime has a __toString
method.

 Also, AFAICT createFromFormat fails if the date is not formatted
 according to the first parameter. So, for example:
 $date = DateTime::createFromFormat('d M Y', '5/2/10')
 fails ... (at least, it does on my system :( )


I'm sorry for asking but what did you expect?? You're specifically
calling a method that parses a string according to a given format. If
it parsed the string according to any other format, that would be a
huge WTF.

Regards
Peter

-- 
hype
WWW: plphp.dk / plind.dk
LinkedIn: plind
BeWelcome/Couchsurfing: Fake51
Twitter: kafe15
/hype 



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



Re: [PHP] Re: Date validation

2011-05-20 Thread Peter Lind
2011/5/20 João Cândido de Souza Neto j...@consultorweb.cnt.br:
 If you look carefully, you´ll notice that I´m using the DateTime object
 (default from PHP 5.2.0 or higher) not the function date.

If you look carefully, you'll notice that I replied to Geoff.

Regards
Peter

-- 
hype
WWW: plphp.dk / plind.dk
LinkedIn: plind
BeWelcome/Couchsurfing: Fake51
Twitter: kafe15
/hype

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



[PHP] Re: Date validation

2011-05-20 Thread Geoff Lane
 On Friday, May 20, 2011, Peter Lind wrote:

 This is pretty much as expected except that the second call to
 date() - i.e. date('d M Y', $date) - outputs nothing.

 date() takes an int as second parameter - a timestamp. Not an object.
 And from a quick test it doesn't look like DateTime has a __toString
 method.

Thanks - my misunderstanding. I'll have to look into that further.

 Also, AFAICT createFromFormat fails if the date is not formatted
 according to the first parameter. So, for example:
  $date = DateTime::createFromFormat('d M Y', '5/2/10')
 fails ... (at least, it does on my system :( )


 I'm sorry for asking but what did you expect?? You're specifically
 calling a method that parses a string according to a given format. If
 it parsed the string according to any other format, that would be a
 huge WTF.

Don't feel sorry to have asked, because it's exactly what I expected.
João suggested using createFromFormat. Since I need to validate dates
input in any valid form, I felt it wouldn't work and my comment was to
João to that effect. That said, I've seen some weird and unexpected
results from my development server recently (e.g. my post of 16 May re
weird cookie behaviour) which was why I added the proviso (at least,
it does on my system) just in case that method wasn't meant to behave
as I inferred.

With all that said, I still have no 'out of the box' method to
validate a user-input date string and I haven't been able to find the
code I used with PHP 3.something before my sojourn into the depths of
ASP to know how I used to do this!

-- 
Geoff


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



Re: [PHP] Re: Date validation

2011-05-20 Thread Peter Lind
On 20 May 2011 16:47, Geoff Lane ge...@gjctech.co.uk wrote:

*snip*

 Also, AFAICT createFromFormat fails if the date is not formatted
 according to the first parameter. So, for example:
  $date = DateTime::createFromFormat('d M Y', '5/2/10')
 fails ... (at least, it does on my system :( )


 I'm sorry for asking but what did you expect?? You're specifically
 calling a method that parses a string according to a given format. If
 it parsed the string according to any other format, that would be a
 huge WTF.

 Don't feel sorry to have asked, because it's exactly what I expected.
 João suggested using createFromFormat. Since I need to validate dates
 input in any valid form, I felt it wouldn't work and my comment was to
 João to that effect. That said, I've seen some weird and unexpected
 results from my development server recently (e.g. my post of 16 May re
 weird cookie behaviour) which was why I added the proviso (at least,
 it does on my system) just in case that method wasn't meant to behave
 as I inferred.

 With all that said, I still have no 'out of the box' method to
 validate a user-input date string and I haven't been able to find the
 code I used with PHP 3.something before my sojourn into the depths of
 ASP to know how I used to do this!


My bad, I jumped into the middle of a thread - sorry.

Try:

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

Regards
Peter

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



[PHP] Re: Date validation

2011-05-20 Thread Geoff Lane
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.

-- 
Geoff


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



[PHP] Re: Date validation

2011-05-20 Thread Geoff Lane
On Friday, May 20, 2011, João Cândido de Souza Neto wrote:

 What about using regular expression to validate so using DateTime
 object to  parse it if it?s a valid date?

Again, thanks.

For info, I only need to know that it's a valid representation of a
date on this occasion as I intend to use the MySQL CAST function to do
the actual conversion within the INSERT or UPDATE SQL statement that
commits the value to the underlying database.

I strongly suspect that you're correct in that I should be able to use
a regexp to do the validation. This could well be the catalyst that
gets my sleeves rolled up, a large pot of strong, black coffee on the
hob, and me finally trying that little bit harder to get my head
around regular expressions!

I was hoping that PHP would have an equivalent to VBScript's IsDate()
function but it looks like I'll have to roll my own!

Thanks again,

-- 
Geoff


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



[PHP] Re: Date Validation, Kinda'

2003-08-21 Thread Scott Fletcher
I did similiar posting about finding the last day of the month last week and
got some response.  So, I'll just post some clipping from php.net for you.
If your machine support the php mktime() then you're in for luck.  You can
find more info about it at php.net with the function, date() and mktime().

--snip--

   //To find out the last day of the month
   echo date (M-d-Y, mktime (0,0,0,12,32,1997));

--snip--

Scott F.

Jay Blanchard [EMAIL PROTECTED] wrote in message
news:[EMAIL PROTECTED]
Howdy,

Has anyone written any date validation function or sequence. I have
looked around, but haven't found anything. I am cobbling togather
something, but was hoping to not have to re-invent the wheel. The date
is formatted MMDD and is input by the user;

$userCentury = substr($userDate, 0, 2); //must be 20 (no problem)
$userYear = substr($userDate, 2, 2); //must be 03 or better
$userMonth = substr($userDate, 4, 2); // 01-12
$userDay = substr($userDate, 6, 2); // 01-31

It doesn't matter if the month is 02 and they have entered 31 as the
day. If any one of the four conditions is not true it gives them a
warning. Anyone done this before?

Thanks!

Jay



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