I am currently using jQuery validation plugin to validate my form fields, named "start date" and "end date". I have my own jQuery validation method that will validate and ensure that the end date will be greater than the start date. However, the weird thing is that if my start date is: 01/06/2017 and my end date is: 01/05/2018, it will prompt me an error saying that "end date should be greater than start date". However, this error should not appear because clearly end date is greater than start date by looking at the values. So what is wrong?
<form id="dataForm" role="form" class="form-horizontal">
<div class="form-group col-md-12">
<label class="control-label col-md-4" for="startDateInput">Start Date</label>
<div class="col-md-7">
<div class="input-group date" style="max-width: 280px" data-provide="datepicker">
<input type="text" class="form-control" id="startDateInput" name="startDateInput">
<div class="input-group-addon">
<span class="glyphicon glyphicon-calendar"></span>
</div>
</div>
</div>
</div>
<div class="form-group col-md-12">
<label class="control-label col-md-4" for="endDateInput">End Date</label>
<div class="col-md-7">
<div class="input-group date" style="max-width: 280px" data-provide="datepicker">
<input type="text" class="form-control" id="endDateInput" name="endDateInput">
<div class="input-group-addon">
<span class="glyphicon glyphicon-calendar"></span>
</div>
</div>
</div>
</div>
<div class="form-group col-md-12">
<label class="control-label col-md-1"></label>
<div class="col-md-10">
<div class="pull-right">
<input type="button" class="btn btn-primary" value="Save" id="saveButton" />
</div>
</div>
</div>
<script>
$('.date').datepicker({
format: 'dd/mm/yyyy',
autoclose: true,
todayHighlight: true
});
$.validator.addMethod("endDate", function (value, element, params) {
var startDate = $('#startDateInput').val();
var endDate = value;
return startDate < endDate || value == "";
}, '*End date must be after start date');
$('#dataForm').validate({
rules: {
startDateInput: {
required: true
},
endDateInput: {
endDate: true
}
}
});
$('#saveButton').on('click', function () {
if ($('#dataForm').valid() == true)
alert('hi');
});
Demo: https://jsfiddle.net/Issaki1/gud7xjy0/31/ Hi, please demo with the following values, start date: 01/06/2017 end date: 01/05/2018