+ 1

Validating textfield for a date, php

i was wondering if there was a way to validate (force) a date input into a textfield? i understand that with textfields, almost any data can be typed in. but i want to force the user to type in a date only into a textfield. formatting is no problem, just validating

23rd Feb 2017, 9:20 PM
Robin
Robin - avatar
7 Réponses
+ 5
RegEx, but always remember that you must aware the user of what date format to use. I'm in England where we use the date/month/year or DD/MM/YYYY format opposed to the US month/date/year or MM/DD/YYYY form. It wouldn't be sufficient using just one pattern to confirm the data. Example if you expect the English form, and a user inputs 12/25/17 this would pass this test; a valid date but not in the right order you originally wanted. /^[0-9]{1,2}\/[0-9]{1,2}\/[0-9]{4}$/ Consider having select options to restrict input - and it's more secure this way - when requiring data, but don't let that put you off.
23rd Feb 2017, 11:55 PM
Mark Foxx
Mark Foxx - avatar
+ 2
function validateDate($date, $format) { $d = DateTime::createFromFormat($format, $date); return $d && $d->format($format) === $date; } it validate any format and returns as boolean
24th Feb 2017, 3:56 AM
Naveen DA
Naveen DA - avatar
+ 1
I think using regex, you will be able to restrict user input and allow only date format.
23rd Feb 2017, 11:12 PM
Dev
Dev - avatar
+ 1
@dev thanks buddy. ill look into that
23rd Feb 2017, 11:14 PM
Robin
Robin - avatar
0
you may used type=date to enter the date in textfield
23rd Feb 2017, 9:28 PM
Salman Mushtaq
Salman Mushtaq - avatar
0
that would work. and it would be easier to go that way. but im looking to get a spacific value typed in without the use of the date type.
23rd Feb 2017, 9:45 PM
Robin
Robin - avatar
0
@robin you're welcome man ;)
23rd Feb 2017, 11:16 PM
Dev
Dev - avatar