0

From an HTML document, I am getting two value

$dateStart = $_GET['date_1']; //date starting search
$dateEnd = $_GET['date_2']; //date starting search

Does PHP offer a feature that allows me to check if the input don't match the format dd/mm/yy or must I nest conditions?

Pete
  • 148
  • 1
  • 12

1 Answers1

1

Validate your date

if (DateTime::createFromFormat('d/m/y', $date)) {
    echo "Date is valid";
} else {
    echo "Date is not valid";
}

More generally, if you want to validate "stuff"

Use PHP "embedded filters" with filter_var(). Link. You can use it for a lot of "standard" filters or with your regex. In the case of dd/mm/yy dates you can use a custom regex:

$regex = '~^\d{2}/\d{2}/\d{2}$~';
print filter_var("01/01/2017",FILTER_VALIDATE_REGEXP,["options" => ["regexp"=> $regex]]);

Beware, this will validate also 22/22/22 which is not correct, so use the first proposed date validation, I used it only as example ;)

napolux
  • 15,574
  • 9
  • 51
  • 70
  • Does this need any external librairies? Can't seem to get it to work. – Pete Mar 17 '17 at 11:34
  • Nevermind. The issue was i wasn't using capital 'y'. Lower case y only takes 2 digits for the year. Thanks for the solution. – Pete Mar 17 '17 at 11:39
  • It doesn't seem to catch everything though. `$dateStart = $_GET['date_1']; if (DateTime::createFromFormat('d/m/Y', $dateStart )){ ` doesn't catch 48/12/1975. – Pete Mar 17 '17 at 11:46
  • That's because is not a valid date. Use regex instead – napolux Mar 17 '17 at 20:49