Blazor playground

Nova v3.37.0

Preview

Blazor

Fielddate

← nv-fielddate

NvFielddate Component - Practical Guide for Blazor Developers

The NvFielddate component is a Blazor wrapper around Nova's date picker component, providing seamless integration with Blazor's data binding, forms, and validation systems. It combines a text input with a calendar popover for date selection.

General Blazor Concepts

For general information about data binding, forms, and validation in Nova Blazor components, see the Nova Blazor Integration Guide. This guide focuses on date picker-specific features and patterns.

Basic Usage

Simple Date Picker

razor<NvFielddate Label="Birth Date" Placeholder="Select your birth date" />

Date Picker with Description

razor<NvFielddate
    Label="Event Date"
    Description="Choose the date for your event"
    Placeholder="YYYY-MM-DD" />

Two-Way Data Binding

The component supports Blazor's @bind-Value syntax for seamless two-way data binding with string values (ISO date format):

Simple Binding

razor@code {
    private string selectedDate = "";
}

<NvFielddate
    @bind-Value="selectedDate"
    Label="Appointment Date"
    Placeholder="Select a date" />

@if (!string.IsNullOrEmpty(selectedDate))
{
    <p>Selected date: @selectedDate</p>
}

Date Binding with DateTime Conversion

razor@code {
    private DateTime? appointmentDate = null;

    private string DateToString(DateTime? date) => date?.ToString("yyyy-MM-dd");
    private DateTime? StringToDate(string value) =>
        string.IsNullOrEmpty(value) ? null : DateTime.Parse(value);
}

<NvFielddate
    Value="@DateToString(appointmentDate)"
    ValueChanged="(value) => appointmentDate = StringToDate(value)"
    Label="Appointment Date" />

@if (appointmentDate.HasValue)
{
    <div class="appointment-info">
        <h4>Appointment Scheduled</h4>
        <p>Date: @appointmentDate.Value.ToString("D")</p>
        <p>Time until appointment: @((appointmentDate.Value - DateTime.Now).Days) days</p>
    </div>
}

Event Handling

Using ValueChanged Event

razor<NvFielddate
    @bind-Value="eventDate"
    Label="Event Date"
    ValueChanged="OnDateChanged"
    Placeholder="Select event date" />

@if (!string.IsNullOrEmpty(eventDate))
{
    <div class="date-validation">
        @if (IsWeekend(eventDate))
        {
            <span class="warning">⚠️ Weekend selected - additional fees may apply</span>
        }
        else
        {
            <span class="success">✓ Weekday selected</span>
        }
    </div>
}

@code {
    private string eventDate = "";

    private void OnDateChanged(string value)
    {
        eventDate = value;
        // Could trigger availability check, price calculation, etc.
    }

    private bool IsWeekend(string dateString)
    {
        if (string.IsNullOrEmpty(dateString)) return false;
        var date = DateTime.Parse(dateString);
        return date.DayOfWeek == DayOfWeek.Saturday || date.DayOfWeek == DayOfWeek.Sunday;
    }
}

Date Range Validation

razor<NvFielddate
    Value="startDate"
    Label="Start Date"
    ValueChanged="OnStartDateChanged"
    Placeholder="Select start date" />

<NvFielddate
    Value="endDate"
    Label="End Date"
    ValueChanged="OnEndDateChanged"
    Placeholder="Select end date" />

@if (!string.IsNullOrEmpty(rangeMessage))
{
    <div class="range-message @rangeMessageType">
        @rangeMessage
    </div>
}

@code {
    private string startDate = "";
    private string endDate = "";
    private string rangeMessage = "";
    private string rangeMessageType = "";

    private void OnStartDateChanged(string value)
    {
        startDate = value;
        ValidateDateRange();
    }

    private void OnEndDateChanged(string value)
    {
        endDate = value;
        ValidateDateRange();
    }

    private void ValidateDateRange()
    {
        if (string.IsNullOrEmpty(startDate) || string.IsNullOrEmpty(endDate))
        {
            rangeMessage = "";
            return;
        }

        if (!DateTime.TryParse(startDate, out var start) ||
            !DateTime.TryParse(endDate, out var end))
        {
            rangeMessage = "Invalid date format";
            rangeMessageType = "error";
            return;
        }

        if (end < start)
        {
            rangeMessage = "End date must be after start date";
            rangeMessageType = "error";
        }
        else if ((end - start).TotalDays > 365)
        {
            rangeMessage = "Date range cannot exceed 1 year";
            rangeMessageType = "warning";
        }
        else
        {
            var days = (end - start).TotalDays;
            rangeMessage = $"✓ Valid range: {days} days";
            rangeMessageType = "success";
        }
    }
}

Date Constraints and Validation

Min/Max Date Constraints

razor<NvFielddate
    @bind-Value="birthDate"
    Label="Date of Birth"
    Min="1900-01-01"
    Max="@DateTime.Now.ToString("yyyy-MM-dd")"
    Placeholder="Select your birth date" />

<NvFielddate
    @bind-Value="graduationDate"
    Label="Expected Graduation"
    Min="@DateTime.Now.ToString("yyyy-MM-dd")"
    Max="@DateTime.Now.AddYears(10).ToString("yyyy-MM-dd")"
    Placeholder="Select graduation date" />

Disabled Dates

razor<NvFielddate
    @bind-Value="appointmentDate"
    Label="Appointment Date"
    DisabledDates="GetDisabledDates()"
    Placeholder="Select available date" />

@code {
    private string appointmentDate = "";

    private string[] GetDisabledDates()
    {
        var disabledDates = new List<string>();
        var today = DateTime.Now;

        // Disable weekends
        for (int i = 0; i < 365; i++)
        {
            var date = today.AddDays(i);
            if (date.DayOfWeek == DayOfWeek.Saturday || date.DayOfWeek == DayOfWeek.Sunday)
            {
                disabledDates.Add(date.ToString("yyyy-MM-dd"));
            }
        }

        // Disable holidays (example)
        disabledDates.AddRange(new[] {
            "2024-12-25", // Christmas
            "2024-01-01", // New Year
            "2024-07-04"  // Independence Day
        });

        return disabledDates.ToArray();
    }
}

Form Integration

The component integrates seamlessly with Blazor's EditForm for validation and form submission:

Basic Form Integration

razor<EditForm Model="bookingModel" OnValidSubmit="CreateBooking">
    <DataAnnotationsValidator />

    <NvFieldtext
        @bind-Value="bookingModel.CustomerName"
        Label="Customer Name"
        For="() => bookingModel.CustomerName" />

    <NvFielddate
        @bind-Value="bookingModel.BookingDate"
        Label="Booking Date"
        Min="@DateTime.Now.ToString("yyyy-MM-dd")"
        For="() => bookingModel.BookingDate" />

    <NvFieldtext
        @bind-Value="bookingModel.Email"
        Label="Email"
        Type="TypeEnum.email"
        For="() => bookingModel.Email" />

    <button type="submit">Create Booking</button>
</EditForm>

@code {
    private BookingModel bookingModel = new();

    private void CreateBooking()
    {
        // Process booking
        Console.WriteLine("Booking created successfully!");
    }

    public class BookingModel
    {
        [Required]
        public string? CustomerName { get; set; }

        [Required(ErrorMessage = "Please select a booking date")]
        public string? BookingDate { get; set; }

        [Required]
        [EmailAddress]
        public string? Email { get; set; }
    }
}

Validation

Required Date Validation

razor<EditForm Model="eventModel" OnValidSubmit="CreateEvent">
    <DataAnnotationsValidator />

    <NvFieldtext
        @bind-Value="eventModel.Title"
        Label="Event Title"
        For="() => eventModel.Title" />

    <NvFielddate
        @bind-Value="eventModel.EventDate"
        Label="Event Date"
        Required="true"
        Min="@DateTime.Now.ToString("yyyy-MM-dd")"
        For="() => eventModel.EventDate" />

    <NvFieldtextarea
        @bind-Value="eventModel.Description"
        Label="Description"
        For="() => eventModel.Description" />

    <button type="submit">Create Event</button>
</EditForm>

@code {
    private EventModel eventModel = new();

    public class EventModel
    {
        [Required]
        public string? Title { get; set; }

        [Required(ErrorMessage = "Please select an event date")]
        public string? EventDate { get; set; }

        public string? Description { get; set; }
    }
}

Custom Date Validation

razor<EditForm Model="projectModel" OnValidSubmit="CreateProject">
    <DataAnnotationsValidator />

    <NvFieldtext
        @bind-Value="projectModel.Name"
        Label="Project Name"
        For="() => projectModel.Name" />

    <NvFielddate
        @bind-Value="projectModel.StartDate"
        Label="Start Date"
        For="() => projectModel.StartDate" />

    <NvFielddate
        @bind-Value="projectModel.EndDate"
        Label="End Date"
        For="() => projectModel.EndDate" />

    <button type="submit">Create Project</button>
</EditForm>

@code {
    private ProjectModel projectModel = new();

    public class ProjectModel
    {
        [Required]
        public string? Name { get; set; }

        [Required]
        [CustomDateValidation]
        public string? StartDate { get; set; }

        [Required]
        [CustomDateValidation]
        public string? EndDate { get; set; }
    }

    public class CustomDateValidationAttribute : ValidationAttribute
    {
        protected override ValidationResult? IsValid(object? value, ValidationContext validationContext)
        {
            var project = (ProjectModel)validationContext.ObjectInstance;
            var dateString = value as string;

            if (string.IsNullOrEmpty(dateString))
                return new ValidationResult("Date is required");

            if (!DateTime.TryParse(dateString, out var date))
                return new ValidationResult("Invalid date format");

            // Business rule validation
            if (project.StartDate != null && project.EndDate != null)
            {
                if (!DateTime.TryParse(project.StartDate, out var startDate) ||
                    !DateTime.TryParse(project.EndDate, out var endDate))
                    return ValidationResult.Success;

                if (endDate < startDate)
                    return new ValidationResult("End date must be after start date");

                if ((endDate - startDate).TotalDays > 365)
                    return new ValidationResult("Project duration cannot exceed 1 year");

                if (startDate < DateTime.Now.Date)
                    return new ValidationResult("Start date cannot be in the past");
            }

            return ValidationResult.Success;
        }
    }
}

Advanced Scenarios

Date Shortcuts

razor<NvFielddate
    @bind-Value="selectedDate"
    Label="Select Date"
    Shortcuts="GetDateShortcuts()"
    ShowActions="true" />

@code {
    private string selectedDate = "";

    private NvFielddateShortcuts[] GetDateShortcuts()
    {
        return new[]
        {
            new NvFielddateShortcuts
            {
                Label = "Today",
                SingleValue = DateTime.Now.ToString("yyyy-MM-dd")
            },
            new NvFielddateShortcuts
            {
                Label = "Tomorrow",
                SingleValue = DateTime.Now.AddDays(1).ToString("yyyy-MM-dd")
            },
            new NvFielddateShortcuts
            {
                Label = "Next Week",
                SingleValue = DateTime.Now.AddDays(7).ToString("yyyy-MM-dd")
            },
            new NvFielddateShortcuts
            {
                Label = "End of Month",
                SingleValue = new DateTime(DateTime.Now.Year, DateTime.Now.Month,
                    DateTime.DaysInMonth(DateTime.Now.Year, DateTime.Now.Month)).ToString("yyyy-MM-dd")
            }
        };
    }
}

Multiple Calendars

razor<NvFielddate
    @bind-Value="vacationStart"
    Label="Vacation Start Date"
    NumberOfCalendars="2"
    Min="@DateTime.Now.ToString("yyyy-MM-dd")"
    Placeholder="Select vacation start" />

<NvFielddate
    @bind-Value="vacationEnd"
    Label="Vacation End Date"
    NumberOfCalendars="2"
    Min="@vacationStart"
    Placeholder="Select vacation end" />

@if (!string.IsNullOrEmpty(vacationStart) && !string.IsNullOrEmpty(vacationEnd))
{
    var start = DateTime.Parse(vacationStart);
    var end = DateTime.Parse(vacationEnd);
    var days = (end - start).TotalDays;

    <div class="vacation-summary">
        <h4>Vacation Summary</h4>
        <p>Duration: @days days</p>
        <p>Return date: @end.ToString("D")</p>
    </div>
}

@code {
    private string vacationStart = "";
    private string vacationEnd = "";
}

Localized Date Picker

razor<div class="locale-examples">
    <NvFielddate
        @bind-Value="usDate"
        Label="US Format"
        Locale="en-US"
        DateFormat="MM/DD/YYYY"
        Placeholder="MM/DD/YYYY" />

    <NvFielddate
        @bind-Value="euDate"
        Label="European Format"
        Locale="en-GB"
        DateFormat="DD/MM/YYYY"
        Placeholder="DD/MM/YYYY" />

    <NvFielddate
        @bind-Value="isoDate"
        Label="ISO Format"
        Locale="en-CA"
        DateFormat="YYYY-MM-DD"
        Placeholder="YYYY-MM-DD" />
</div>

@code {
    private string usDate = "";
    private string euDate = "";
    private string isoDate = "";
}

Date Picker with Week Numbers

razor<NvFielddate
    @bind-Value="meetingDate"
    Label="Meeting Date"
    ShowWeekNumbers="true"
    FirstDayOfWeek="1"
    Placeholder="Select meeting date" />

@if (!string.IsNullOrEmpty(meetingDate))
{
    var date = DateTime.Parse(meetingDate);
    var weekNumber = System.Globalization.ISOWeek.GetWeekOfYear(date);

    <div class="meeting-info">
        <p>Meeting scheduled for: @date.ToString("D")</p>
        <p>Week number: @weekNumber</p>
        <p>Day of week: @date.DayOfWeek</p>
    </div>
}

@code {
    private string meetingDate = "";
}

Age Calculator

razor<NvFielddate
    @bind-Value="birthDate"
    Label="Date of Birth"
    Max="@DateTime.Now.ToString("yyyy-MM-dd")"
    ValueChanged="CalculateAge"
    Placeholder="Select birth date" />

@if (!string.IsNullOrEmpty(birthDate))
{
    <div class="age-info">
        <h4>Age Information</h4>
        <p>Birth Date: @DateTime.Parse(birthDate).ToString("D")</p>
        <p>Current Age: @age years, @months months, @days days</p>
        <p>Next Birthday: @nextBirthday.ToString("D")</p>
    </div>
}

@code {
    private string birthDate = "";
    private int age = 0;
    private int months = 0;
    private int days = 0;
    private DateTime nextBirthday = DateTime.MinValue;

    private void CalculateAge(string value)
    {
        if (string.IsNullOrEmpty(value)) return;

        var birth = DateTime.Parse(value);
        var today = DateTime.Now;

        age = today.Year - birth.Year;
        if (birth.Date > today.AddYears(-age)) age--;

        var lastBirthday = birth.AddYears(age);
        var timeSinceLastBirthday = today - lastBirthday;

        months = (int)timeSinceLastBirthday.TotalDays / 30;
        days = (int)timeSinceLastBirthday.TotalDays % 30;

        nextBirthday = birth.AddYears(age + 1);
    }
}

Best Practices

  1. Use appropriate date formats for your target audience (ISO for technical, localized for users)
  2. Always set min/max constraints to prevent invalid date selection
  3. Provide clear validation messages for date-related errors
  4. Consider using shortcuts for commonly selected dates
  5. Handle date parsing carefully with proper error handling
  6. Use disabled dates to prevent selection of invalid dates
  7. Consider localization for international applications
  8. Test date edge cases like leap years, DST changes, timezone issues
  9. Provide visual feedback for date validation and constraints
  10. Consider mobile users - date pickers should be touch-friendly

Common Patterns

User Registration

razor<EditForm Model="userRegistration" OnValidSubmit="RegisterUser">
    <DataAnnotationsValidator />

    <NvFieldtext
        @bind-Value="userRegistration.FirstName"
        Label="First Name"
        For="() => userRegistration.FirstName" />

    <NvFieldtext
        @bind-Value="userRegistration.LastName"
        Label="Last Name"
        For="() => userRegistration.LastName" />

    <NvFielddate
        @bind-Value="userRegistration.DateOfBirth"
        Label="Date of Birth"
        Max="@DateTime.Now.ToString("yyyy-MM-dd")"
        For="() => userRegistration.DateOfBirth" />

    <NvFieldtext
        @bind-Value="userRegistration.Email"
        Label="Email"
        Type="TypeEnum.email"
        For="() => userRegistration.Email" />

    <button type="submit">Register</button>
</EditForm>

@code {
    private UserRegistrationModel userRegistration = new();

    public class UserRegistrationModel
    {
        [Required]
        public string? FirstName { get; set; }

        [Required]
        public string? LastName { get; set; }

        [Required]
        public string? DateOfBirth { get; set; }

        [Required]
        [EmailAddress]
        public string? Email { get; set; }
    }
}

Event Planning

razor<EditForm Model="eventPlanning" OnValidSubmit="CreateEvent">
    <DataAnnotationsValidator />

    <NvFieldtext
        @bind-Value="eventPlanning.Title"
        Label="Event Title"
        For="() => eventPlanning.Title" />

    <NvFieldtextarea
        @bind-Value="eventPlanning.Description"
        Label="Description"
        For="() => eventPlanning.Description" />

    <NvFielddate
        @bind-Value="eventPlanning.StartDate"
        Label="Start Date"
        Min="@DateTime.Now.ToString("yyyy-MM-dd")"
        For="() => eventPlanning.StartDate" />

    <NvFielddate
        @bind-Value="eventPlanning.EndDate"
        Label="End Date"
        Min="@eventPlanning.StartDate"
        For="() => eventPlanning.EndDate" />

    <NvFieldnumber
        @bind-Value="eventPlanning.MaxAttendees"
        Label="Maximum Attendees"
        Min="1"
        Max="1000"
        For="() => eventPlanning.MaxAttendees" />

    <button type="submit">Create Event</button>
</EditForm>

@code {
    private EventPlanningModel eventPlanning = new();

    public class EventPlanningModel
    {
        [Required]
        public string? Title { get; set; }

        public string? Description { get; set; }

        [Required]
        public string? StartDate { get; set; }

        [Required]
        public string? EndDate { get; set; }

        [Required]
        [Range(1, 1000)]
        public double? MaxAttendees { get; set; }
    }
}

This guide covers the most common use cases and patterns for the NvFielddate component in Blazor applications. For more advanced scenarios or specific requirements, refer to the component's API documentation or the Storybook examples.