简体   繁体   中英

Date validation with input type date

I have two types of date, I need to check the end date should greater than start date.

These are two input:

<input id="startdate" type="date" name="startdate" />

<input id="enddate" type="date" name="enddate" />
<div class="errmsg" id="errmsg"></div>

I need if the end date less than start date (show error message in errmsg div)

$startdate = strtotime($_POST['startdate']);
$enddate = strtotime($_POST['enddate']);

if ($enddate < $startdate) {
$error = 'Error!';
}

echo $error;

You can use strtotime for html5 input date type

<?php
    $startdate= $_POST['startdate'];
    $enddate= $_POST['enddate'];

    $start = strtotime($startdate);
    $end = strtotime($enddate);
    if($end < $start){
        //show error
    }
?>

A suggestion here:

First, your input could be located in a form:

<form action='action_code.php' method="post">
     <input id="startdate" type="date" name="startdate"  /> 
     <input id="enddate" type="date" name="enddate" />
     <input type="submit" value="Submit"> 
</form>

and the action_code.php file would contain:

<?php

$startdate = $_POST['startdate'];
$enddate = $_POST['enddate'];

if($enddate < $startdate){
    echo 'enddate has to be after startdate';
}else{
    echo 'form submitted';
    echo $startdate;
    echo $enddate;
}    

echo '<a href="/home.php">Back home</a>';
?>

What is to retain here is that dates can be compared using comparison operators likewise numbers. I omitted any formatting in order to keep the code clean.

You can use checkdate () for date validate checkdate php.net

$date = $_POST['enddate'];
$test_date = explode('/', $date);
if (count($test_date) == 3)
{
    if (checkdate($test_date[0], $test_date[1], $test_date[2])) {
        //  date is  valid
    }
    else
    {
        // Invalid date dates
    }
} else
{
    // invalid input
}

And to compare two date

$today_dt = strtotime($_POST['startdate']);
$expire_dt = strtotime($_POST['enddate']);

if ($expire_dt < $today_dt)
{
    /* Do something */
}

Refer this answer

use jquery as

$("#enddate").keyup(function(){
var startDate = $('#startdate').val().replace('-','/');
var endDate = $('#enddate').val().replace('-','/');

if(startDate > endDate){
    $('#errmsg').html('Start time must be smaller than End time');
}else{
    $('#errmsg').html('');
}
});

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