Simple datepicker validation

2020-02-16 02:12发布

Can someone help me write a function for showing a line of text (preferably by showing a css class) for a jquery datepicker after someone has clicked a date?

The notice has to appear IF the date picked falls between TODAY and 21 DAYS FROM TODAY.

It's the function I need help with, as I don't know how to write it.

<script>
     $(function() {
          $( "#delivery_date" ).datepicker({ 
                dateFormat: "dd/mm/yy",
          });
     });
 </script>

<input type="text" id="delivery_date" name="delivery_date" required  />

3条回答
虎瘦雄心在
2楼-- · 2020-02-16 02:50

just use onSelect property when you init datepicker

$( "#delivery_date" ).datepicker({ 
    dateFormat: "dd/mm/yy",
    minDate : new Date(),
    onSelect: function(str) {

        var lastDate = new Date(),
            nums = str.split("/"),
            userDate = new Date(nums[2], nums[1]-1, nums[0]), // reverse date
            period = 21;

        lastDate.setDate(lastDate.getDate()+period);

        if (userDate<lastDate) {
            // notify
            alert("inside 21 days period");
        }
    }
});

try FIDDLE

查看更多
Lonely孤独者°
3楼-- · 2020-02-16 02:55

U can use onClose in datepicker

$(function() {
  $( "#date" ).datepicker({ 
  dateFormat: "dd/mm/yy",
  onClose: function() {
        valid();
    }
  });
});

jsfiddle - example

查看更多
够拽才男人
4楼-- · 2020-02-16 03:05

You might be able to validate it using date.js, it has a fluent API which makes it very easy to express your conditions.

Example code might be:

var enteredDate = $("#delivery_date").prop("value");
var parsed = Date.parse(enteredDate); 
var start = Date.today();
var end = Date.today().add(21).days(); 
if (!parsed.between(start, end)) {
    alert("Date is valid");
} else {
    alert("Date is not valid");
}

Test plunker

查看更多
登录 后发表回答