0

I'm trying to access the format of a given date value. I need to check whether the format is in dd/mm/yy or dd/mm/yyyy. I have used the following patterns with preg_match(), but they do not work.

'^\d{1,2}\/\d{1,2}\/\d{4}^'  //  dd/mm/yyyy

'^\d{1,2}\/\d{1,2}\/\d{2}^'  //  dd/mm/yy

Can someone help me to find the correct pattern?

mickmackusa
  • 43,625
  • 12
  • 83
  • 136
US-1234
  • 1,519
  • 4
  • 24
  • 61
  • This is an error caused by simple typographical errors that could have been identified by testing at www.regex101.com or doing a quick bit of research on regex syntax / reading SO pages. This pattern and the accepted answer will at best do a loose validation of the date. In other words, invalid dates like `99/99/9999` will be matched without a problem. For best results use `checkdate()` or DateTime class functions to validate a date. – mickmackusa Aug 24 '17 at 21:44
  • Notice how the best [answers on this page](https://stackoverflow.com/questions/19271381/correctly-determine-if-date-string-is-a-valid-date-in-that-format) do not use regex, and the ones that do only improve in quality as the pattern exponentially grows. Using regex is not the best tool for checking dates. – mickmackusa Aug 24 '17 at 21:50

2 Answers2

1

Problems:

1. This $ should be in end instead of ^. $ is for end of string.

2. Don't forget delimiters /.

Regular expression:

/^\d{1,2}\/\d{1,2}\/\d{4}$/ for strings like 10/10/1111

/^\d{1,2}\/\d{1,2}\/\d{2}$/ for strings like 10/10/11

Try this code snippet here

Community
  • 1
  • 1
Sahil Gulati
  • 15,028
  • 4
  • 24
  • 42
0

You have an error in the syntax of your regular expression. In a regex, the start of the pattern is denoted by ^ while the end is by $.

You can use the following to validate the given date format.

$date_to_check = "22/06/2017";
$true = preg_match("/([0-9]{2})\/([0-9]{2})\/([0-9]{4})/", $date_to_check);
var_dump($true);

However, you shouldn't be validating a date against a regex expression only. You need to pass the Year, month, date to the php's checkdate() function to really validate it.

PHP checkdate() doc

Nimeshka Srimal
  • 8,012
  • 5
  • 42
  • 57