Codeigniter - Date format - Form Validation

2019-01-17 23:31发布

问题:

I'm using codeigniter with PHP. I'm using following form,

<?php
    echo form_open('/register/create_new', $form_params);
?>

DOB: <input type="text" id="dob" name="reg[dob]">
     <input type="submit" value="Create Account" />
</form>

here, #dob is in dd-mm-yyyy format.

my validation code is,

array(
  'field' => 'reg[dob]',
  'label' => 'DOB',
  'rules' => 'required'
)

How can i set the rules for correct date validation?

回答1:

you can do it with regex

$this->form_validation->set_rules('reg[dob]', 'Date of birth', 'regex_match[(0[1-9]|1[0-9]|2[0-9]|3(0|1))-(0[1-9]|1[0-2])-\d{4}]'); 


回答2:

You can take use of CodeIgniters callback functions by creating a callback_date_valid() function that check if the date is valid.

And to check if it is valid, you could use PHP's checkdate function

array(
  'field' => 'reg[dob]',
  'label' => 'DOB',
  'rules' => 'required|date_valid'
)

function callback_date_valid($date){
    $day = (int) substr($date, 0, 2);
    $month = (int) substr($date, 3, 2);
    $year = (int) substr($date, 6, 4);
    return checkdate($month, $day, $year);
}


回答3:

I have a pretty clean solution for this. You can extend codeigniters form validation library.

Do this by putting a MY_Form_validation.php file in your application/libraries folder. This file should look like this:

class MY_Form_validation extends CI_Form_validation {

public function __construct($rules = array())
{
    parent::__construct($rules);
}


public function valid_date($date)
{
    $d = DateTime::createFromFormat('Y-m-d', $date);
    return $d && $d->format('Y-m-d') === $date;
}
}

To add the error message, you go to your application/language/ folder and open the form_validation_lang.php file. Add an entry to the $lang array at the end of the file, like so:

$lang['form_validation_valid_date'] = 'The field {field} is not a valid date';

Note that the key here must be the same as the function name (valid_date).

Then in your controller you use this as any other form validation function like for example 'required'

$this->form_validation->set_rules('date','Date','trim|required|valid_date');


回答4:

I know this is old, but I just encountered the same issue. I like the answer Winks provided, but found that the code did not work. I modified it to this:

  public function your_form_handler($date)
  {
    // ....
    $this->form_validation->set_rules('date', 'Date', 'required|callback_date_valid');
    // ....
  }

  /**
   * Validate dd/mm/yyyy
   */
  public function date_valid($date)
  {
    $parts = explode("/", $date);
    if (count($parts) == 3) {      
      if (checkdate($parts[1], $parts[0], $parts[2]))
      {
        return TRUE;
      }
    }
    $this->form_validation->set_message('date_valid', 'The Date field must be mm/dd/yyyy');
    return false;
  }


回答5:

There is no builtin date validation in Codeigniter form_validation Library, but you can use its callback to call a function and validate the date using PHP's own capabilities.

With DateTime you can make the shortest date&time validator for all formats.

function validateDate($date, $format = 'Y-m-d H:i:s')
{
    $d = DateTime::createFromFormat($format, $date);
    return $d && $d->format($format) == $date;
}

var_dump(validateDate('2012-02-28 12:12:12')); # true
var_dump(validateDate('2012-02-30 12:12:12')); # false
var_dump(validateDate('2012-02-28', 'Y-m-d')); # true
var_dump(validateDate('28/02/2012', 'd/m/Y')); # true
var_dump(validateDate('30/02/2012', 'd/m/Y')); # false
var_dump(validateDate('14:50', 'H:i')); # true
var_dump(validateDate('14:77', 'H:i')); # false
var_dump(validateDate(14, 'H')); # true
var_dump(validateDate('14', 'H')); # true

var_dump(validateDate('2012-02-28T12:12:12+02:00', 'Y-m-d\TH:i:sP')); # true
# or
var_dump(validateDate('2012-02-28T12:12:12+02:00', DateTime::ATOM)); # true

var_dump(validateDate('Tue, 28 Feb 2012 12:12:12 +0200', 'D, d M Y H:i:s O')); # true
# or
var_dump(validateDate('Tue, 28 Feb 2012 12:12:12 +0200', DateTime::RSS)); # true
var_dump(validateDate('Tue, 27 Feb 2012 12:12:12 +0200', DateTime::RSS)); # false

function was copied from this answer or php.net



回答6:

I like the answer tmsimont provided, but found that the code did not work if non numeric values enterd. Modified code is given below:

/**
    * Validate dd/mm/yyyy
    */
    public function date_valid(){
        $date=$this->input->post('dob');
        $parts = explode("/", $date);
        if (count($parts) == 3) {     
            if (is_numeric($parts[2])) {  
                if (is_numeric($parts[0])) {
                    if (is_numeric($parts[1])) {    
                        if (checkdate($parts[1], $parts[0], $parts[2])){
                            return TRUE;
                        }
                    }
                }
            }
        }

        $this->form_validation->set_message('date_valid', 'The Date field must be mm/dd/yyyy');
        return false;
    }


回答7:

The actual Regex for Codeigniter Date validation :

$this->form_validation->set_rules('reg[dob]','Date of birth',array('regex_match[/^((0[1-9]|[12][0-9]|3[01])[- \/.](0[1-9]|1[012])[- \/.](19|20)\d\d)$/]'));

I am using same expression for format dd-mm-yyyy and dd/mm/yyyy

No Warnings and errors :-)



回答8:

I've written this custom validator for ci3 - validates the d/m/Y H:i format - you can easily change that.

$this->form_validation->set_rules("start_date", "Start Date", 'trim|callback__check_date_valid');


   public function _check_date_valid($date){

    $this->form_validation->set_message('_check_date_valid', "Please enter a valid date");
    $d = DateTime::createFromFormat('d/m/Y H:i', $date);

    if($d && $d->format('d/m/Y H:i') === $date || $date == ''){
        return true;
    }else{

        return false;
    }

}


回答9:

Using Regex is probably the best way. I use this Regex that I found here for the format YYYY-MM-DD: http://www.regular-expressions.info/dates.html

The actual Regex is:

^(19|20)\d\d[- /.](0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])$

It has a nice explanation on how each section works so that you can modify it for different date formats.

Then you can use the code suggested by @Abin: (make sure you enclose it in some kind of delimiter)

$this->form_validation->set_rules('reg[dob]', 'Date of birth', 'regex_match[/^(19|20)\d\d[- /.](0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])$/]');