tags:

views:

29

answers:

2

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 to show them a Popup message if it's not a valid date.

Can anybody help me out?

thanks

+3  A: 

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: http://stackoverflow.com/questions/2968414/#2973696

$("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/

patrick dw
+1 - I would combine this with disabling them in the datepicker itself as well, feel free to include this code in your answer: http://stackoverflow.com/questions/2968414/#2973696
Nick Craver
@Nick - Thanks, I'll include your code. +1 on your linked answer. :o)
patrick dw
Thanks Nick, but how to validate 1/1 and 1/25 each year?
kumar
@kumar - Like this: http://jsfiddle.net/UwcLf/2/
Nick Craver
@Nick - Thanks. I was a little slow on the uptake on that one! Posted a similar version in my answer, then saw that you already had one. :o)
patrick dw
+1  A: 

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.

Russ C