0

I am modifying an existing project, where I want to validate the start date(From) and end date(To) using jquery. The requirement is that End date(To) cannot be less than the Start date(from). Below is my html code and I add the jquery code I've written. But the date is not validated and it doesn't display any error message. Once I click the submit button it submit successfully without any error. I refer the following question to write the jquery part, but does not work. I really appreciate if some one can help me to resolve this. Thanks in advance.

Using jquery Validation 'greaterthan' function

var validator = $("#add_cetificate").validate();

$("#valid_to").rules('add', { greaterThan: "#valid_from" });


 
 $.validator.addMethod('greaterThan', function(value, element, param){   
        var startDate =  $(param).val();
         var endDate = value ;
        return endDate > startDate;

 });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.1/jquery.validate.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.1/additional-methods.min.js"></script>
<div class="form-group">
    <label for="" class="col-sm-2 control-label">Valid From<span class="star"> * </span></label>
    <div class="col-sm-3">
        <input type="text" class="form-control datepicker" name="valid_from[]" id="valid_from" required="required">
    </div>
    <label for="" class="col-sm-2 control-label"> To <span class="star"> * </span></label>
    <div class="col-sm-3">
        <input type="text" class="form-control datepicker" name="valid_to[]" id="valid_to" required="required">
    </div>
</div>
Kash
  • 329
  • 3
  • 15
  • which datepicker have you used? – Prateik Darji Jan 31 '20 at 10:52
  • @PrateikDarji, I don't know how to find it, since i am modifying an existing project, can you please tell me how to find it – Kash Jan 31 '20 at 14:26
  • @PrateikDarji, there is a jquery for datepicker as `$('.datepicker').datepicker({ format: 'yyyy-mm-dd', autoclose: true });` – Kash Jan 31 '20 at 15:08
  • then you should check for datetime plugin for this type of condition instead of creating validator method. – Prateik Darji Feb 01 '20 at 08:07
  • Does this answer your question? [JQuery - end date less than start date](https://stackoverflow.com/questions/19317678/jquery-end-date-less-than-start-date) – Prateik Darji Feb 01 '20 at 08:18
  • @PrateikDarji, I Edited my jquery validation part. Now it works, But when i am adding another start date and end date (Before submitting one set of dates, user can again add another date set as per requirement ) it doesnot validate. I think the value of name attribute of dates is an array(valid_from[]). I don't know it correctly. Is it an array value? – Kash Feb 01 '20 at 10:57

0 Answers0