Blazor playground

Nova v3.37.0

Preview

Blazor

Fieldtime

← nv-fieldtime

NvFieldtime Component - Practical Guide for Blazor Developers

The NvFieldtime component is a Blazor wrapper around Nova's time picker component, providing seamless integration with Blazor's data binding, forms, and validation systems. It supports multiple time formats and includes a time picker popover.

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 time picker-specific features and patterns.

Basic Usage

Simple Time Picker

razor<NvFieldtime Label="Meeting Time" Placeholder="Select time" />

Time Picker with Description

razor<NvFieldtime
    Label="Appointment Time"
    Description="Please select your preferred appointment time"
    Format="FormatEnum.HHmm" />

Two-Way Data Binding

The component supports Blazor's @bind-Value syntax for seamless two-way data binding with string values in the specified time format:

Simple Binding

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

<NvFieldtime
    @bind-Value="selectedTime"
    Label="Start Time"
    Format="FormatEnum.HHmm" />

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

Time Range Selection

razor@code {
    private string startTime = "";
    private string endTime = "";
}

<NvFieldtime
    @bind-Value="startTime"
    Label="Start Time"
    Format="FormatEnum.HHmm"
    ValueChanged="ValidateTimeRange" />

<NvFieldtime
    @bind-Value="endTime"
    Label="End Time"
    Format="FormatEnum.HHmm"
    ValueChanged="ValidateTimeRange" />

@if (!string.IsNullOrEmpty(startTime) && !string.IsNullOrEmpty(endTime))
{
    var start = TimeSpan.Parse(startTime);
    var end = TimeSpan.Parse(endTime);
    var duration = end - start;

    <div class="time-summary">
        <p>Duration: @duration.TotalHours hours</p>
    </div>
}

@code {
    private void ValidateTimeRange(string value)
    {
        if (!string.IsNullOrEmpty(startTime) && !string.IsNullOrEmpty(endTime))
        {
            var start = TimeSpan.Parse(startTime);
            var end = TimeSpan.Parse(endTime);

            if (end <= start)
            {
                // Handle validation error
            }
        }
    }
}

Time Formats

Different Time Formats

razor<NvFieldtime
    @bind-Value="hourOnly"
    Label="Hour Only"
    Format="FormatEnum.HH"
    Placeholder="HH" />

<NvFieldtime
    @bind-Value="hourMinute"
    Label="Hour and Minute"
    Format="FormatEnum.HHmm"
    Placeholder="HH:mm" />

<NvFieldtime
    @bind-Value="fullTime"
    Label="Full Time"
    Format="FormatEnum.HHmmss"
    Placeholder="HH:mm:ss" />

<NvFieldtime
    @bind-Value="hour12"
    Label="12-Hour Format"
    Format="FormatEnum.hhmm"
    Placeholder="hh:mm" />

@code {
    private string hourOnly = "";
    private string hourMinute = "";
    private string fullTime = "";
    private string hour12 = "";
}

Event Handling

Using ValueChanged Event

razor<NvFieldtime
    @bind-Value="meetingTime"
    Label="Meeting Time"
    Format="FormatEnum.HHmm"
    ValueChanged="OnTimeSelected" />

@if (!string.IsNullOrEmpty(meetingTime))
{
    <div class="time-info">
        <h4>Meeting Scheduled</h4>
        <p>Time: @meetingTime</p>
        @if (IsBusinessHours(meetingTime))
        {
            <span class="success">✓ Business hours</span>
        }
        else
        {
            <span class="warning">⚠️ Outside business hours</span>
        }
    </div>
}

@code {
    private string meetingTime = "";

    private void OnTimeSelected(string value)
    {
        meetingTime = value;
        // Could trigger availability check, calendar updates, etc.
    }

    private bool IsBusinessHours(string timeString)
    {
        if (string.IsNullOrEmpty(timeString)) return false;
        var time = TimeSpan.Parse(timeString);
        return time >= TimeSpan.FromHours(9) && time <= TimeSpan.FromHours(17);
    }
}

Time Validation

razor@code {
    private string workStart = "";
    private string workEnd = "";
    private string validationMessage = "";

    private void OnTimeChanged(string value)
    {
        ValidateWorkHours();
    }

    private void ValidateWorkHours()
    {
        if (string.IsNullOrEmpty(workStart) || string.IsNullOrEmpty(workEnd))
        {
            validationMessage = "";
            return;
        }

        try
        {
            var start = TimeSpan.Parse(workStart);
            var end = TimeSpan.Parse(workEnd);

            if (end <= start)
            {
                validationMessage = "End time must be after start time";
            }
            else if ((end - start).TotalHours > 12)
            {
                validationMessage = "Work day cannot exceed 12 hours";
            }
            else if ((end - start).TotalHours < 4)
            {
                validationMessage = "Work day must be at least 4 hours";
            }
            else
            {
                validationMessage = "✓ Valid work hours";
            }
        }
        catch
        {
            validationMessage = "Invalid time format";
        }
    }
}

<NvFieldtime
    @bind-Value="workStart"
    Label="Work Start Time"
    Format="FormatEnum.HHmm"
    ValueChanged="OnTimeChanged" />

<NvFieldtime
    @bind-Value="workEnd"
    Label="Work End Time"
    Format="FormatEnum.HHmm"
    ValueChanged="OnTimeChanged" />

@if (!string.IsNullOrEmpty(validationMessage))
{
    <div class="validation-message">@validationMessage</div>
}

Time Constraints

Min/Max Time Constraints

razor<NvFieldtime
    @bind-Value="businessHours"
    Label="Business Hours"
    Format="FormatEnum.HHmm"
    Min="09:00"
    Max="17:00"
    Placeholder="Select business hours" />

<NvFieldtime
    @bind-Value="lunchBreak"
    Label="Lunch Break"
    Format="FormatEnum.HHmm"
    Min="12:00"
    Max="14:00"
    Placeholder="Select lunch time" />

Step Intervals

razor<NvFieldtime
    @bind-Value="quarterHour"
    Label="Quarter Hour Intervals"
    Format="FormatEnum.HHmm"
    Step="900000" /> <!-- 15 minutes in milliseconds -->

<NvFieldtime
    @bind-Value="halfHour"
    Label="Half Hour Intervals"
    Format="FormatEnum.HHmm"
    Step="1800000" /> <!-- 30 minutes in milliseconds -->

@code {
    private string quarterHour = "";
    private string halfHour = "";
}

Form Integration

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

Basic Form Integration

razor<EditForm Model="appointmentModel" OnValidSubmit="ScheduleAppointment">
    <DataAnnotationsValidator />

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

    <NvFieldtime
        @bind-Value="appointmentModel.Time"
        Label="Appointment Time"
        Format="FormatEnum.HHmm"
        Min="09:00"
        Max="17:00"
        For="() => appointmentModel.Time" />

    <NvFieldtext
        @bind-Value="appointmentModel.Description"
        Label="Description"
        For="() => appointmentModel.Description" />

    <button type="submit">Schedule Appointment</button>
</EditForm>

@code {
    private AppointmentModel appointmentModel = new();

    private void ScheduleAppointment()
    {
        // Process appointment scheduling
        Console.WriteLine("Appointment scheduled successfully!");
    }

    public class AppointmentModel
    {
        [Required]
        public string? Date { get; set; }

        [Required(ErrorMessage = "Please select an appointment time")]
        public string? Time { get; set; }

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

Validation

Required Time Validation

razor<EditForm Model="scheduleModel" OnValidSubmit="CreateSchedule">
    <DataAnnotationsValidator />

    <NvFieldtime
        @bind-Value="scheduleModel.StartTime"
        Label="Start Time"
        Format="FormatEnum.HHmm"
        Required="true"
        For="() => scheduleModel.StartTime" />

    <NvFieldtime
        @bind-Value="scheduleModel.EndTime"
        Label="End Time"
        Format="FormatEnum.HHmm"
        Required="true"
        For="() => scheduleModel.EndTime" />

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

@code {
    private ScheduleModel scheduleModel = new();

    public class ScheduleModel
    {
        [Required(ErrorMessage = "Start time is required")]
        public string? StartTime { get; set; }

        [Required(ErrorMessage = "End time is required")]
        public string? EndTime { get; set; }
    }
}

Custom Time Validation

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

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

    <NvFieldtime
        @bind-Value="eventModel.StartTime"
        Label="Start Time"
        Format="FormatEnum.HHmm"
        For="() => eventModel.StartTime" />

    <NvFieldtime
        @bind-Value="eventModel.EndTime"
        Label="End Time"
        Format="FormatEnum.HHmm"
        For="() => eventModel.EndTime" />

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

@code {
    private EventModel eventModel = new();

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

        [Required]
        [CustomTimeValidation]
        public string? StartTime { get; set; }

        [Required]
        [CustomTimeValidation]
        public string? EndTime { get; set; }
    }

    public class CustomTimeValidationAttribute : ValidationAttribute
    {
        protected override ValidationResult? IsValid(object? value, ValidationContext validationContext)
        {
            var eventModel = (EventModel)validationContext.ObjectInstance;
            var timeString = value as string;

            if (string.IsNullOrEmpty(timeString))
                return new ValidationResult("Time is required");

            if (!TimeSpan.TryParse(timeString, out var time))
                return new ValidationResult("Invalid time format");

            // Business rule validation
            if (eventModel.StartTime != null && eventModel.EndTime != null)
            {
                if (!TimeSpan.TryParse(eventModel.StartTime, out var startTime) ||
                    !TimeSpan.TryParse(eventModel.EndTime, out var endTime))
                    return ValidationResult.Success;

                if (endTime <= startTime)
                    return new ValidationResult("End time must be after start time");

                if ((endTime - startTime).TotalHours > 8)
                    return new ValidationResult("Event duration cannot exceed 8 hours");

                if (startTime < TimeSpan.FromHours(6))
                    return new ValidationResult("Events cannot start before 6:00 AM");

                if (endTime > TimeSpan.FromHours(22))
                    return new ValidationResult("Events cannot end after 10:00 PM");
            }

            return ValidationResult.Success;
        }
    }
}

Advanced Scenarios

Time Zone Conversion

razor<NvFieldtime
    @bind-Value="localTime"
    Label="Local Time"
    Format="FormatEnum.HHmm"
    ValueChanged="ConvertTimeZones" />

<div class="timezone-conversions">
    <h4>Time in Different Zones</h4>
    <p>UTC: @utcTime</p>
    <p>EST: @estTime</p>
    <p>PST: @pstTime</p>
    <p>CET: @cetTime</p>
</div>

@code {
    private string localTime = "";
    private string utcTime = "";
    private string estTime = "";
    private string pstTime = "";
    private string cetTime = "";

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

        var local = TimeSpan.Parse(value);
        var utc = local; // Assuming local is already UTC for simplicity

        // Convert to different timezones (simplified)
        estTime = (utc - TimeSpan.FromHours(5)).ToString(@"hh\:mm");
        pstTime = (utc - TimeSpan.FromHours(8)).ToString(@"hh\:mm");
        cetTime = (utc + TimeSpan.FromHours(1)).ToString(@"hh\:mm");
        utcTime = utc.ToString(@"hh\:mm");
    }
}

Meeting Scheduler

razor<EditForm Model="meetingModel" OnValidSubmit="ScheduleMeeting">
    <DataAnnotationsValidator />

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

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

    <NvFieldtime
        @bind-Value="meetingModel.StartTime"
        Label="Start Time"
        Format="FormatEnum.HHmm"
        Min="09:00"
        Max="17:00"
        For="() => meetingModel.StartTime" />

    <NvFieldtime
        @bind-Value="meetingModel.EndTime"
        Label="End Time"
        Format="FormatEnum.HHmm"
        Min="@meetingModel.StartTime"
        Max="18:00"
        For="() => meetingModel.EndTime" />

    <NvFieldnumber
        @bind-Value="meetingModel.Duration"
        Label="Duration (hours)"
        Min="0.5"
        Max="8"
        Step="0.5"
        For="() => meetingModel.Duration" />

    <button type="submit">Schedule Meeting</button>
</EditForm>

@code {
    private MeetingModel meetingModel = new();

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

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

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

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

        [Required]
        [Range(0.5, 8)]
        public double? Duration { get; set; }
    }
}

Alarm Clock Settings

razor<div class="alarm-settings">
    <h3>Alarm Settings</h3>

    <NvFieldtime
        @bind-Value="alarmTime"
        Label="Alarm Time"
        Format="FormatEnum.HHmm"
        Placeholder="Set alarm time" />

    @if (!string.IsNullOrEmpty(alarmTime))
    {
        var alarm = TimeSpan.Parse(alarmTime);
        var now = DateTime.Now.TimeOfDay;
        var timeUntilAlarm = alarm > now ?
            alarm - now :
            TimeSpan.FromDays(1) + alarm - now;

        <div class="alarm-info">
            <p>Alarm set for: @alarm.ToString(@"hh\:mm tt")</p>
            <p>Time until alarm: @timeUntilAlarm.Hours hours @timeUntilAlarm.Minutes minutes</p>
        </div>
    }

    <div class="alarm-options">
        <NvFieldcheckbox
            @bind-Checked="repeatDaily"
            Label="Repeat daily" />

        <NvFieldcheckbox
            @bind-Checked="snoozeEnabled"
            Label="Enable snooze" />
    </div>
</div>

@code {
    private string alarmTime = "";
    private bool repeatDaily = false;
    private bool snoozeEnabled = true;
}

Restaurant Reservation

razor<EditForm Model="reservationModel" OnValidSubmit="MakeReservation">
    <DataAnnotationsValidator />

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

    <NvFieldtext
        @bind-Value="reservationModel.Phone"
        Label="Phone Number"
        Type="TypeEnum.tel"
        For="() => reservationModel.Phone" />

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

    <NvFieldtime
        @bind-Value="reservationModel.Time"
        Label="Reservation Time"
        Format="FormatEnum.HHmm"
        Min="11:00"
        Max="22:00"
        For="() => reservationModel.Time" />

    <NvFieldnumber
        @bind-Value="reservationModel.Guests"
        Label="Number of Guests"
        Min="1"
        Max="20"
        For="() => reservationModel.Guests" />

    <button type="submit">Make Reservation</button>
</EditForm>

@code {
    private ReservationModel reservationModel = new();

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

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

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

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

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

Work Schedule Calculator

razor<NvFieldtime
    @bind-Value="clockIn"
    Label="Clock In Time"
    Format="FormatEnum.HHmm"
    ValueChanged="CalculateWorkHours" />

<NvFieldtime
    @bind-Value="clockOut"
    Label="Clock Out Time"
    Format="FormatEnum.HHmm"
    ValueChanged="CalculateWorkHours" />

@if (!string.IsNullOrEmpty(clockIn) && !string.IsNullOrEmpty(clockOut))
{
    <div class="work-summary">
        <h4>Work Summary</h4>
        <p>Clock In: @clockIn</p>
        <p>Clock Out: @clockOut</p>
        <p>Hours Worked: @hoursWorked</p>
        <p>Overtime: @overtimeHours hours</p>
        <p>Regular Pay: $@regularPay</p>
        <p>Overtime Pay: $@overtimePay</p>
        <p>Total Pay: $@totalPay</p>
    </div>
}

@code {
    private string clockIn = "";
    private string clockOut = "";
    private string hoursWorked = "0.00";
    private string overtimeHours = "0.00";
    private string regularPay = "0.00";
    private string overtimePay = "0.00";
    private string totalPay = "0.00";

    private void CalculateWorkHours(string value)
    {
        if (string.IsNullOrEmpty(clockIn) || string.IsNullOrEmpty(clockOut)) return;

        var start = TimeSpan.Parse(clockIn);
        var end = TimeSpan.Parse(clockOut);

        var totalHours = (end - start).TotalHours;
        var regularHours = Math.Min(totalHours, 8);
        var overtime = Math.Max(totalHours - 8, 0);

        hoursWorked = totalHours.ToString("F2");
        overtimeHours = overtime.ToString("F2");

        const decimal hourlyRate = 25.00m;
        const decimal overtimeRate = 37.50m;

        regularPay = (regularHours * (double)hourlyRate).ToString("F2");
        overtimePay = (overtime * (double)overtimeRate).ToString("F2");
        totalPay = ((regularHours * (double)hourlyRate) + (overtime * (double)overtimeRate)).ToString("F2");
    }
}

Best Practices

  1. Choose appropriate time formats based on use case (HH:mm for most scheduling, HH:mm:ss for precise timing)
  2. Set min/max constraints to prevent invalid time selection
  3. Use step intervals that make sense for the context (15 min for appointments, 1 hour for meetings)
  4. Consider 12-hour vs 24-hour formats based on target audience
  5. Validate time ranges properly for scheduling applications
  6. Handle timezone conversions carefully if needed
  7. Provide clear labels explaining what the time represents
  8. Test time edge cases like midnight, noon, and daylight saving transitions
  9. Consider mobile users - time pickers should be touch-friendly
  10. Provide visual feedback for time validation and constraints

Common Patterns

Appointment Booking

razor<EditForm Model="appointmentModel" OnValidSubmit="BookAppointment">
    <DataAnnotationsValidator />

    <NvFieldtext
        @bind-Value="appointmentModel.PatientName"
        Label="Patient Name"
        For="() => appointmentModel.PatientName" />

    <NvFielddate
        @bind-Value="appointmentModel.AppointmentDate"
        Label="Appointment Date"
        Min="@DateTime.Now.ToString("yyyy-MM-dd")"
        For="() => appointmentModel.AppointmentDate" />

    <NvFieldtime
        @bind-Value="appointmentModel.AppointmentTime"
        Label="Appointment Time"
        Format="FormatEnum.HHmm"
        Min="09:00"
        Max="17:00"
        For="() => appointmentModel.AppointmentTime" />

    <NvFieldselect
        @bind-Value="appointmentModel.Doctor"
        Label="Select Doctor"
        Options="doctorOptions"
        For="() => appointmentModel.Doctor" />

    <button type="submit">Book Appointment</button>
</EditForm>

@code {
    private AppointmentModel appointmentModel = new();

    public class AppointmentModel
    {
        [Required]
        public string? PatientName { get; set; }

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

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

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

    private NvFieldselectOptions[] doctorOptions = new[]
    {
        new NvFieldselectOptions { Label = "Dr. Smith", Value = "smith" },
        new NvFieldselectOptions { Label = "Dr. Johnson", Value = "johnson" },
        new NvFieldselectOptions { Label = "Dr. Williams", Value = "williams" }
    };
}

Event Creation

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

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

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

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

    <NvFieldtime
        @bind-Value="eventModel.StartTime"
        Label="Start Time"
        Format="FormatEnum.HHmm"
        For="() => eventModel.StartTime" />

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

    <NvFieldtime
        @bind-Value="eventModel.EndTime"
        Label="End Time"
        Format="FormatEnum.HHmm"
        For="() => eventModel.EndTime" />

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

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

@code {
    private EventModel eventModel = new();

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

        public string? Description { get; set; }

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

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

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

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

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

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