简体   繁体   中英

Validating a date dd/mm/yyyy

Does anyone know of any good functions for validating a date via input text box in codeigniter like this: dd/mm/yyyy? Thanks

You're probably looking for the strptime function. For the specified format you can use it like this:

$result = strptime($input, '%d/%m/%Y');

$result will be either false if the input is invalid or on array with the date.

Or if you're on Windows or have PHP >= 5.3, consider using date_parse_from_format .

Use strtotime function.

$date = strtotime($input);

returns false if invalid, or -1 for php4.

you could also use a custom callback function

<?php

function valid_date($date)
{
    $date_format = 'd-m-Y'; /* use dashes - dd/mm/yyyy */

    $date = trim($date);
    /* UK dates and strtotime() don't work with slashes, 
    so just do a quick replace */
    $date = str_replace('/', '-', $date); 


    $time = strtotime($date);

    $is_valid = date($date_format, $time) == $date;

    if($is_valid)
    {
        return true;
    }

    /* not a valid date..return false */
    return false;
}
?>

your validation rule looks like:

$rules['your_date_field'] = "callback_valid_date";

不了解codeigniter,但是在php中已经有一些类似的东西checkdate();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM