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?
CodeIgniter lets you set as many validation rules as you need for a given field, cascading them in order, and it even lets you prep and pre-process the field data at the same time. To set validation rules you will use the set_rules() method: $this->form_validation->set_rules();
PHP | checkdate() Function The checkdate() function is a built-in function in PHP which checks the validity of the date passed in the arguments. It accepts the date in the format mm/dd/yyyy. The function returns a boolean value. It returns true if the date is a valid one, else it returns false.
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);
}
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');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With