Mathi
Mathi

Reputation: 159

jQuery Date Validation while explicitly type on the input field

jQuery Date Validation while explicitly type on the input field instead of selecting from datepicker

I just want minimum date as today. i.e I don't want to select future dates.

In date picker i disabled the future dates.But, when i type the date in the field it is accepting the future date.

Here is my jQuery Code

jQuery(document).ready(function() {
  jQuery("#datepicker").datepicker({  maxDate: new Date(),dateFormat: 'MM/DD/YYYY' });
  jQuery('.fa-calendar').click(function() {
    jQuery("#datepicker").focus();
  });
});

Upvotes: 2

Views: 2446

Answers (2)

Ataur Rahman Munna
Ataur Rahman Munna

Reputation: 3917

I think probably you are looking for something like this. you can give input date by typing and validate it that not greater than today. I would also suggest that to use your datepicker field readonly so that user can not give invalid input as @Mufi said in the comment.

$(document).ready(function() {
  $("#datepicker,#datepickerReadonly").datepicker({  
  	maxDate: new Date(),
  	dateFormat: 'dd/mm/yy',
	changeYear:true,
	changeMonth:true,
  });
  
  $('.fa-calendar').click(function() {
    $("#datepicker").focus();
  });
  
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" rel="stylesheet"/>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

<input type="text" id="datepicker">
<input type="button" id="" value="check" onclick="check_();"/><br>
Read Only Example: <br><input type="text" readonly="readonly" id="datepickerReadonly">

<script>
function check_(){
	if(new Date($('#datepicker').val()) > new Date()){
		alert("you are not allowed to select future date");
		$('#datepicker').val('');
	}
}
</script>

Upvotes: 3

Ashiquzzaman
Ashiquzzaman

Reputation: 5284

Try this:

jQuery(document).ready(function() {

      jQuery("#datepicker").datepicker({                         
                    dateFormat: 'MM/DD/YYYY',
                    maxDate: '+10Y',
                    minDate: '+0M',
                    changeMonth: true,
                    changeYear: true,
                    yearRange: "-0:+10", });

      jQuery('.fa-calendar').click(function() {
        jQuery("#datepicker").focus();
      });
    });

This example allow you to select maximum 10 years previous year to Today.

Upvotes: 0

Related Questions