验证日期

时间:2018-04-08 05:51:49

标签: php forms validation

我试图在注册表格/类型中验证出生日期 - 日期/。但是当提交表格时,验证通过。日期必须介于1900年至今之间。这是我的代码:

$min = \DateTime::createFromFormat('m/d/Y', '01/01/1900');
$max = date('Y-m-d', time());

if ($user->getBirthDate() < $min || $user->getBirthDate() > $max) {
        throw new \PDOException("Invalid date");
}

选择上一个日期时的验证通过,例如2018年3月3日

2 个答案:

答案 0 :(得分:1)

$(document).ready(function() {
    $('#rangeForm').bootstrapValidator({
        feedbackIcons: {
            valid: 'glyphicon glyphicon-ok',
            invalid: 'glyphicon glyphicon-remove',
            validating: 'glyphicon glyphicon-refresh'
        },
        fields: {
            date: {
                validators: {
                    date: {
                        message: 'The date is not valid',
                        format: 'YYYY/MM/DD'
                    },
                    callback: {
                        message: 'The date is not in the range',
                        callback: function(value, validator) {
                            var m = new moment(value, 'YYYY/MM/DD', true);
                            if (!m.isValid()) {
                                return false;
                            }
                            return m.isAfter('2000/01/01') && m.isBefore('2020/12/30');
                        }
                    }
                }
            }
        }
    });
});
<!-- Include the momentjs library to use later -->
<script src="//oss.maxcdn.com/momentjs/2.8.2/moment.min.js"></script>

<form id="rangeForm" class="form-horizontal">
    <div class="form-group">
        <label class="col-sm-6 control-label">Enter a date between 2000/01/01 and 2020/12/30</label>
        <div class="col-sm-3">
            <input type="text" class="form-control" name="date" />
        </div>
    </div>
</form>

答案 1 :(得分:0)

这可以帮助您更好地解决问题

<?php

class Blar_DateTime extends DateTime {
    public function __toString() {
        return $this->format('Y-m-d');
            }
}

$min = new Blar_DateTime('1900-01-01');
$max = date('Y-m-d', time());
if(isset($_POST['submit'])){
try { 
    $userbirthdate=$_POST['getBirthDate'];
if (($userbirthdate < $min) || ($userbirthdate > $max)) {
        throw new Exception('Invalid date');
}
} catch (Exception $e) {
    echo 'Caught exception: ',  $e->getMessage(), "\n";
}
}
?>
<!DOCTYPE html>
<html>
<body>
<form id="tmp_name" name="tmp_name" method="POST" action="">
<input type="date" id="getBirthDate" name="getBirthDate" value="">
<input type="submit" name="submit" value="submit">
</form>
</body>
</html>