Viewed   118 times

I'm trying to check that dates entered by end users are in the YYYY-MM-DD. Regex has never been my strong point, I keep getting a false return value for the preg_match() I have setup.

So I'm assuming I have made a mess of the regex, detailed below.

$date="2012-09-12";

if (preg_match("^[0-9]{4}-[0-1][0-9]-[0-3][0-9]$",$date))
    {
        return true;
    }else{
        return false;
    }

Any thoughts?

 Answers

4

Try this.

$date="2012-09-12";

if (preg_match("/^[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])$/",$date)) {
    return true;
} else {
    return false;
}
Sunday, October 16, 2022
4
function _date_is_valid($str) {
    if (substr_count($str, '/') == 2) {
        list($d, $m, $y) = explode('/', $str);
        return checkdate($m, $d, sprintf('%04u', $y));
    }

    return false;
}
Monday, September 26, 2022
5

As far as I'm aware, there's no guaranteed way of working backwards. The best way might be to try to match regular expressions against expected well-known formats (e.g. d{2,4}[-/]d{2}[-/]d{2} for "Y-m-d") but I can't think of an easy way to do the matching without using regular expressions. You would also have to check that the parsed format makes sense, and you can't do much about ambiguous dates like 2nd of March 2009, which could be represented as 09/03/02, 2009-03-02, 02/03/09, 03/02/09, or even 09/02/03.

Sunday, December 25, 2022
2

What you need is anchors, specifically ^ and $. The former matches the beginning of the string, the latter matches the end.

The other point I would make is the [] are unnecessary. d retains its meaning outside of character ranges.

So your regex should look like this: /^d{4}-d{2}-d{2}$/.

Thursday, October 13, 2022
1

I went through the same problem some months back.I Just deleted the birthdate field changes in all the migration Files inside migration folder. Then I replaced the birthdate with this code:-

birthdate = models.DateTimeField(blank=True, null=True)                            

Then after applying migration ,it works fine...

Sunday, October 23, 2022
 
Only authorized users can answer the search term. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :