Reputation: 557
Working on a form whereby am using bootstrap datepicker to display date to the user. I have a date of birth field whereby am trying to disable years of any user that is below 18 years from the current date. For instance since we are in 2019, the datepicker should only show years below 2001 e.g 2001 , 2000, 1999 , 1998 , 1997 etc
This works fine (years) but I have a problem disabling the months and the specific days, For instance since we are in 01/02/2019 , the datepicker should disable any date after 1st February 2001
Date of birth
//dob
<div class="form-line registar love">
<input type="text" placeholder="Date of Birth *" class="form-input" name="dob" id="dob" value="#" title="You should be over 18 years old" required>
<label class="error error-tip" for="dob" id="dobErr" style="display: none; color:red; font-size: 11px;">You should be over 18 years old</label>
</div>
//end dob
Javascript Logic
var maxBirthdayDate = new Date();
maxBirthdayDate.setFullYear( maxBirthdayDate.getFullYear() - 18 );
maxBirthdayDate.setMonth(11,31);
$( function() {
$( "#dob" ).datepicker({
changeMonth: true,
changeYear: true,
dateFormat: 'yy-mm-dd',
maxDate: maxBirthdayDate,
yearRange: '1900:'+maxBirthdayDate.getFullYear(),
});
});
Upvotes: 2
Views: 5393
Reputation: 6733
You can validate using minDate
and maxDate
in very simple way to prevent users selecting DOB before 18 years.
$("#dob").datepicker( { minDate: '-30Y',dateFormat: 'dd/mm/yy', maxDate: '-18Y' });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://code.jquery.com/ui/1.10.0/themes/base/jquery-ui.css" />
<script src="https://code.jquery.com/ui/1.10.0/jquery-ui.js"></script>
<p>Date: <input type="text" id="dob" /></p>
Upvotes: 1
Reputation: 2023
for bootstrap-datepicker (^1.9.0) I have solved it using.
$('#dob').datepicker({ endDate: '-18Y' });
Upvotes: 2
Reputation: 2271
with JS date and bootstrap datepicker :
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth() + 1; //January is 0!
var yyyy = today.getFullYear() -18;
if (dd < 10) {
dd = '0' + dd;
}
if (mm < 10) {
mm = '0' + mm;
}
var yearsago = mm + '/' + dd + '/' + yyyy;
or with Moment.js
var yearsago = moment(new Date()).subtract(18, 'years').format("DD-MM-YYYY");
$('#dob').datepicker('setStartDate', yearsago);
or
$('#dob').datepicker({
startDate: yearsago
});
Upvotes: 0