javascript - JQuery validate date between a date range -
this question has answer here:
i've input field users can insert date between date range.
so added new method on jquery validator object:
$.validator.addmethod("daterange", function(value, element, from, to){ try { var date = new date(value); if(date >= && date <= to) return true; } catch(e) { } return false; }
then added new class rules:
$.validator.addclassrules({ mydatefieldrangevalidate: { daterange: {fromdate, todate} } });
and added class input:
$("#myfield").addclass("mydatefieldrangevalidate");
so, how can pass 2 dates validation function?
update: added code snippet
$.validator.addmethod("daterange", function(value, element, from, to){ try { var date = new date(value); if(date >= && date <= to) return true; } catch(e) { } return false; }); var fromdate = new date("2017-02-01"); var todate = new date("2017-12-31"); $.validator.addclassrules({ mydatefieldrangevalidate: { daterange: {fromdate, todate} } }); $("#myfield").addclass("mydatefieldrangevalidate"); $("#btnvalidate").click(function(){ $("#frm1").validate(); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.16.0/additional-methods.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.16.0/jquery.validate.min.js"></script> <form id="frm1"> date <input type="text" id="myfield"> <input type="button" id="btnvalidate" value="validate"> </form>
here way have jquery validator feature give start date , end date
<script src="//ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.16.0/jquery.validate.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.16.0/additional-methods.js"></script> <script> $( document ).ready(function() { // add method. calls 1 built-in method, too. jquery.validator.addmethod("optdate", function(value, element) { var startdate= new date(jquery(element)[0].attributes['data-rule-startdate'].value); var enddate= new date(jquery(element)[0].attributes['data-rule-enddate'].value); var d = new date(value); console.log(d) return (d.gettime() <= enddate.gettime() && d.gettime() >= startdate.gettime()) }, "please enter valid date." ); $('#frm1').validate(); }); </script> <html> <form id="frm1"> date <input type="text" id="myfield" name="myfield" data-rule-optdate="true" data-rule-startdate="2017-12-12" data-rule-enddate="2018-12-12"> </form> </html>
Comments
Post a Comment