开发者

How to validate datepicker to forbid/reject certain dates?

开发者 https://www.devze.com 2023-01-02 08:34 出处:网络
I have this Calendar Control I am using. A user can select any date from the calendar. I need to validate the dates like Saturday and Sundays and 1/1 and 1/25. If they select these days I need t开发者

I have this Calendar Control I am using. A user can select any date from the calendar. I need to validate the dates like Saturday and Sundays and 1/1 and 1/25. If they select these days I need t开发者_如何转开发o show them a Popup message if it's not a valid date.


Try this:

$("input[id^='Date-<%=Model.ID%>']").change(function() {
    var date = new Date($(this).val()).getDay();
    if(date == 0 || date == 6) {
        alert('weekend');
    }
});

This is set up with a change event. Your event may be different.

It get's the value of the input: $(this).val()

Creates a new Date object from it: new Date($(this).val())

Then gets the day number: .getDay() which returns a value from 0 to 6 with 0 being Sunday and 6 being Saturday.

Then you just test for 0 or 6.

Live Example: http://jsfiddle.net/UwcLf/


EDIT: Courtesy of Nick Craver, you can disable specific days if you have no need to run alternate code for weekend selections.

From Nick's linked answer: Disable specific days of the week on jQuery UI datepicker

$("input[id^='Date-<%=Model.ID%>']").datepicker({
    beforeShowDay: function(date) {
        var day = date.getDay();
        return [(day != 0 && day != 6)];
    }
})​​​​​;​

Updated Example: http://jsfiddle.net/UwcLf/1/

Added array for disabled days: http://jsfiddle.net/UwcLf/3/


If you're using the JQUery UI DatePicker, it has an onSelect event, you could use this to validate the selected date.

I don't know your back-end, or if you're using one, but you could always send the selected date to your server via an Ajax call and determine if it's valid or not.

Have a look at Custom Validators if you're using ASP.Net.

0

精彩评论

暂无评论...
验证码 换一张
取 消