Does anyone know how to validate date. For example, cannot have 30 Feb, and no 31 in certain month so when the user enter the valid it will be rejected. I was think about a call back function but not sure how it will be done.
Create a call back function using PHP checkdate function
Use this guide to create callback functions in Codeigniter.
try this the code also takes leap year into account
function valid_date($date)
{
$pattern = '/^(?:(?:31(\/|-|\.)(?:0?[13578]|1[02]))\1|(?:(?:29|30)(\/|-|\.)(?:0?[1,3-9]|1[0-2])\2))(?:(?:1[6-9]|[2-9]\d)?\d{2})$|^(?:29(\/|-|\.)0?2\3(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))$|^(?:0?[1-9]|1\d|2[0-8])(\/|-|\.)(?:(?:0?[1-9])|(?:1[0-2]))\4(?:(?:1[6-9]|[2-9]\d)?\d{2})$/';
if(preg_match($pattern, $date) )
{
return true;
}
else
{
$this->form_validation->set_message('valid_date', 'The %s is not valid it should match this dd/md/yyyy format');
return false;
}
}
//and just use this to set rules
$this->form_validation->set_rules('Your date field from html', 'date', 'required|callback_valid_date');
You can use simple regex to validate the date in dd-mm-yyyy format
$this->form_validation->set_rules('dob', 'Date in dd-mm-yyyy',
'regex_match[(0[1-9]|1[0-9]|2[0-9]|3(0|1))-(0[1-9]|1[0-2])-\d{4}]');
for validation using callback this will make sure of month Feb which is 28 days use this
//Add a rule for validation
$this->form_validation->set_rules('dob', 'Date of Birth', 'callback_valid_date');
//Define a callback and pass the format of date
public function valid_date($date, $format = 'Y-m-d')
{
$d = DateTime::createFromFormat($format, $date);
//Check for valid date in given format
if($d && $d->format($format) == $date) {
return true;
} else {
$this->form_validation->set_message('valid_date',
'The %s date is not valid it should match this ('.$format.') format');
return false;
}
}
Related
I'm new in codeigniter, im trying to create a function that accepts datetime input from a user. If the input is 2 or more days ahead of current datetime, it should return true, if not it should return false.
//my controller looks like this:
public function checkDateTimeInput(){
$dateTimeInput = $this->input->post('dateTimeInput');
if($dateTimeInput /*Greater than 2 days or more*/){
return true;
}else{
return false;
}
}
//in my view:
<?php echo form_open('schedules/checkDateTimeInput'); ?>
<input type="datetime-local" name="dateTimeInput">
<input type="submit" value="submit">
</form>
You could use DateTime() today +2 day to get the next 2 days :
public function checkDateTimeInput(){
$dateTimeInput = new DateTime($this->input->post('dateTimeInput'));
$next_days = new DateTime('today +2 day');
if($dateTimeInput > $next_days) { /*Greater than 2 days or more*/
return true;
}else{
return false;
}
}
You should try this in your controller, The below given code is for 12 hour format
//my controller looks like this:
public function checkDateTimeInput() {
// date_default_timezone_set("Asia/Kolkata"); // make sure you have set it to yours in config file
$date1 = date('Y-m-d h:i:sa', strtotime('+2 days'));
$posted_date_time = date('Y-m-d h:i:sa', strtotime($this->input->post('dateTimeInput')));
if($posted_date_time >= $date1){
//return true;
echo "True";
}
else {
//return false;
echo "False";
}
}
Okay,so in my mysql database I use a date field. Using PHP I check if the user is 18 years of age or not. Then I try to enter all the form information to my MySQL database to make a user. I keep getting a blank screen (besides my navbar and footer) The user is not being saved into the database, and the error log shows this error: PHP Recoverable fatal error: Object of class DateTime could not be converted to string in ....
$age = checkAge($_POST["birthday"]);
if($age != false)
{
$ageSuc = "All Good!";
}
else ....
function checkAge ($data)
{
$dateObj = new DateTime($data);
$ageLimit = new DateTime('-18 years');
if ($dateObj > $ageLimit)
{
return false;
}
else
{
$dateObj->format('Y-m-d');
return $dateObj;
}
}
So the question is, do I need to convert the dateTime Obj into a string before MySQL will accept it? The field is set to hold 'dates' so I thought the date obj would be the same thing? How does one change it to a string.
You are returning the DateTime object, because the format function returns a string, it doesn't change the object. Try returning the result of the format function which is the formatted string.
return $dateObj->format('Y-m-d');
$age = checkAge($_POST["birthday"]);
if($age != false)
{
$ageSuc = "All Good!";
}
else ....
function checkAge ($data)
{
$dateObj = new DateTime($data);
$ageLimit = new DateTime('-18 years');
if ($dateObj > $ageLimit)
{
return false;
}
else
{
return $dateObj->format('Y-m-d');
}
}
If you want a string result, you have to return the format() result, not the object itself.
But the error you have specified is not triggered directly in this code, but somewhere in the else, where you try to convert the result to string.
I have checked that the input date is a valid date, now need to check for backward date where date_start must be before date_end.
I have tried several other option to no avail, I really dont want to compare the substring of the input if possible.
The input are from html5 date using chrome with format dd/mm/yyyy
class MY_Form_validation extends CI_Form_validation {
public $CI;
public function date_format($date) {
if (($timestamp = strtotime($date)) === false) {
return false;
}
}
//error message stored in caller module language folder
public function backward_date($date_start, $date_end) {
$date_1 = new DateTime($date_start);
$date_2 = new DateTime($date_end);
if ($date_1 > $date_2 == true) {
return false;
}
else {
return true;
}
}
}
try this one
public function backward_date($date_start, $date_end) {
$ts1 = strtotime($date_start);
$ts2 = strtotime($date_end);
$seconds_diff = $ts2 - $ts1;
return ($seconds_diff>0) ? true : false;
}
The problem here is that DateTime is not able to parse the string from 'dd/mm/yyyy' to a valid DateTime Object.
Here is the received error :
PHP Warning: Uncaught Exception: DateTime::__construct(): Failed to parse time string (27/10/2017)
In order to fix this, you could use the createFromFormat() method from the DateTime model to parse your string with a specified format.
$date_1 = DateTime::createFromFormat('d/m/Y', $date_start);
So your method would be like :
public function backward_date($date_start, $date_end)
{
$date_1 = DateTime::createFromFormat('d/m/Y', $date_start);
$date_2 = DateTime::createFromFormat('d/m/Y', $date_end);
return $date_1 <= $date_2;
}
Hope it helps.
Try to this ... Working for me.
function date_calculate($start_date, $end_date) {
$dStart = new DateTime($start_date);
$dEnd = new DateTime($end_date);
$days=0;
if ($dStart < $dEnd) {
$dDiff = $dStart->diff($dEnd);
$dDiff->format('%R');
$days = $dDiff->days;
return $days;
} else {
return $days;
}
}
I want to check if value is other than integer and float, i have written form validation as follows,
$this->form_validation->set_rules('charge_hour', 'Per hour', 'xss_clean|callback_money_type');
$this->form_validation->set_rules('charge_day', 'Per day', 'xss_clean|callback_money_type');
$this->form_validation->set_rules('charge_weekly', 'Per week', 'xss_clean|callback_money_type');
$this->form_validation->set_rules('charge_monthly', 'Per month', 'xss_clean|callback_money_type');
and common call back function for all text filed is money_type()
public function money_type($charge)
{
if (is_float($charge) == false && is_int($charge) == false && $charge >= 0)
{
$this->form_validation->set_message('{WHAT TO ENTER HERE}', 'Enter valid charges for space.');
return FALSE;
}
else
{
return TRUE;
}
}
How can I find out during validation that {WHAT TO ENTER HERE}? field name is either of charge_hour, charge_day, charge_weekly, charge_monthly at runtime? so that form validation will show different error messages for each field.
Thanks.
$this->form_validation->set_message('money_type','%s my message');
https://www.codeigniter.com/user_guide/libraries/form_validation.html#callbacks-your-own-validation-methods
You can pass your file name in your callback parameter
$this->form_validation->set_rules('charge_hour', 'Per hour', 'xss_clean|callback_money_type[charge_hour]');
$this->form_validation->set_rules('charge_day', 'Per day', 'xss_clean|callback_money_type[charge_day]');
$this->form_validation->set_rules('charge_weekly', 'Per week', 'xss_clean|callback_money_type[charge_weekly]');
$this->form_validation->set_rules('charge_monthly', 'Per month', 'xss_clean|callback_money_type[charge_monthly]');
You callbacke function
public function money_type($charge,$fild_name)
{
if (is_float($charge) == false && is_int($charge) == false &&
$charge >= 0)
{
$this->form_validation->set_message("{$fild_name}", 'Enter valid charges for space.');
return FALSE;
}
else
{
return TRUE;
}
}
I got the answer, my mistake here.
{WHAT TO ENTER HERE} Should be same as callback function name function money_type , then it will work for all fields callbacks
$this->form_validation->set_message('{WHAT TO ENTER HERE}', 'Enter valid charges for space.');
Should be
$this->form_validation->set_message('money_type', 'Enter valid charges for space.');
I am trying to check if today's date is = 04/01/2013 in a PHP file.
I have written the following JS Script.
But I am getting some error. Dont know why.
Please help
//This function will return if today is the date that we are looking for
function isToday($time) // midnight second
{
alert('1');
return (strtotime($time) === strtotime('today'));
}
Testing using the following:
if (isToday('2013-04-01 00:00:00.0') )
{
alert('Yes true');
}
else
{
alert("No false');
}
Please help how to compare today date = 04/01/2013. Thanks.
If you want to do a date/time compare in JavaScript, you will be best off checking this question asked previously:
Javascript equivalent of php's strtotime()?
That is a strtotime equivalent in JavaScript.
Here's a brief example:
var d = new Date("2013-04-01");
if(d == new Date()) {
alert('yes')
} else {
alert('no')
}
In PHP:
// Get the time
$serverDate = date('d/m/Y',time());
// Date to check against
$dateToCheck = '04/01/2013';
if($dateToCheck == $serverDate) {
alert('Yes true');
} else {
alert('No false');
}