New to Telerik UI for Blazor? Download free 30-day trial

Disable Weekends in the Calendar

Environment

Product Calendar for Blazor, DatePicker for Blazor, DateRangePicker for Blazor

Description

I want to disable the weekends in the Calendar Month view, so the user is not able to select them.

Solution

You can create a collection of weekend days and pass it to the Disabled Dates parameter of the Calendar. This will prevent the user from selecting them.

To achieve that:

  • Set Min and Max parameters of the Calendar.
  • Loop through all the dates between Min and Max.
  • Get only the dates that are Saturday or Sunday.
  • Save them in a collection and pass it to the Disabled Dates parameter of the Calendar.

The example below demonstrates this approach.

At the time of writing, k-disabled class is not applied to all disabled cells . So, in case you need to target all the disabled cells and customize them (for example, add some custom CSS to the disabled cells), use the [aria-disabled="true"] selector.

Pass the weekends to the Disabled Dates collection and disable all weekends between the Min and Max Value of the Calendar.

<style>
    /*Ensure that all disabled cells have the same styles.
      Not neccessary when this is fixed https://feedback.telerik.com/blazor/1539828-k-state-disabled-class-is-not-applied-to-all-disabled-cells */

    [aria-disabled="true"] {
        outline: none;
        opacity: 0.6;
        filter: grayscale(0.1);
        pointer-events: none;
        box-shadow: none;
    }
</style>

<TelerikCalendar Min="@min"
                 Max="@max"
                 View="@View"
                 DisabledDates="@DisabledDates"
                 @bind-Date="@theDate">
</TelerikCalendar>

@code {

    IEnumerable<DateTime> GetDaysBetween(DateTime start, DateTime end)
    {
        for (DateTime i = start; i < end; i = i.AddDays(1))
        {
            yield return i;
        }
    }

    protected override async Task OnInitializedAsync()
    {
        IEnumerable<DateTime> GetDaysBetween(DateTime start, DateTime end)
        {
            for (DateTime i = start; i < end; i = i.AddDays(1))
            {
                yield return i;
            }
        }

        var weekends = GetDaysBetween(min, max)
            .Where(d => d.DayOfWeek == DayOfWeek.Saturday || d.DayOfWeek == DayOfWeek.Sunday);

        DisabledDates = new List<DateTime>(weekends);
    }

    private List<DateTime> DisabledDates = new List<DateTime>();

    public CalendarView View { get; set; } = CalendarView.Month;

    private DateTime min = new DateTime(2020, 1, 1);

    private DateTime max = new DateTime(2025, 12, 31);

    private DateTime theDate { get; set; } = DateTime.Now;

}
In this article
Not finding the help you need? Improve this article