Forms Guide for Nova Design System in Blazor
Introduction
Building robust forms in Blazor applications using Nova's design system requires understanding Blazor's data binding mechanics, validation patterns, and form state management. This guide provides code-centric examples demonstrating how to correctly implement data binding, manage validation, and handle form submission state using Nova's field components.
Key Principles:
- Two-Way Binding: Use
@bind-Valuefor seamless data synchronization - Validation Integration: Leverage Blazor's
EditFormandDataAnnotationsValidatorwith theForparameter - State Management: Handle form submission states (loading, success, error) appropriately
- User Experience: Provide clear feedback and validation messages
Form Architecture
Nova forms in Blazor follow a layered architecture:
- EditForm: Blazor's form component providing validation context
- DataAnnotationsValidator: Enables model-based validation
- Nova Field Components: UI components with built-in accessibility and styling
- Model Classes: Data models with validation attributes
Basic Form Structure
<EditForm Model="formModel" OnValidSubmit="HandleValidSubmit" OnInvalidSubmit="HandleInvalidSubmit">
<DataAnnotationsValidator />
<!-- Nova field components go here -->
<NvButton Type="submit" Loading="isSubmitting">
@if (isSubmitting) { Submit } else { Submitting... }
</NvButton>
</EditForm>
@code {
private FormModel formModel = new();
private bool isSubmitting = false;
private async Task HandleValidSubmit()
{
isSubmitting = true;
try
{
// Form submission logic
await SubmitForm(formModel);
}
finally
{
isSubmitting = false;
}
}
private void HandleInvalidSubmit()
{
// Handle validation errors
}
}
Data Binding Patterns
One-Way Binding
For read-only or controlled scenarios:
<NvFieldtext
Value="userName"
Label="Username"
Readonly="true" />
@code {
private string userName = "john_doe";
}
Two-Way Binding
For interactive forms with automatic synchronization:
<NvFieldtext
@bind-Value="userName"
Label="Username"
Placeholder="Enter username" />
<p>Current value: @userName</p>
@code {
private string userName = "";
}
Event-Driven Binding
For custom logic on value changes:
<NvFieldtext
Value="searchTerm"
Label="Search"
ValueChanged="OnSearchChanged"
Placeholder="Type to search..." />
@code {
private string searchTerm = "";
private void OnSearchChanged(string value)
{
searchTerm = value;
// Perform search logic
PerformSearch(value);
}
}
Validation Strategies
Model-Based Validation
Using DataAnnotations with the For parameter:
<EditForm Model="loginModel" OnValidSubmit="HandleLogin">
<DataAnnotationsValidator />
<NvFieldtext
@bind-Value="loginModel.Email"
Label="Email Address"
Type="TypeEnum.email"
For="() => loginModel.Email" />
<NvFieldtext
@bind-Value="loginModel.Password"
Label="Password"
Type="TypeEnum.password"
For="() => loginModel.Password" />
<NvButton Type="submit">Sign In</NvButton>
</EditForm>
@code {
private LoginModel loginModel = new();
public class LoginModel
{
[Required(ErrorMessage = "Email is required")]
[EmailAddress(ErrorMessage = "Please enter a valid email address")]
public string? Email { get; set; }
[Required(ErrorMessage = "Password is required")]
[MinLength(8, ErrorMessage = "Password must be at least 8 characters")]
public string? Password { get; set; }
}
}
Complex Validation Rules
<EditForm Model="registrationModel" OnValidSubmit="HandleRegistration">
<DataAnnotationsValidator />
<NvFieldtext
@bind-Value="registrationModel.Password"
Label="Password"
Type="TypeEnum.password"
For="() => registrationModel.Password" />
<NvFieldtext
@bind-Value="registrationModel.ConfirmPassword"
Label="Confirm Password"
Type="TypeEnum.password"
For="() => registrationModel.ConfirmPassword" />
<NvButton Type="submit">Register</NvButton>
</EditForm>
@code {
private RegistrationModel registrationModel = new();
public class RegistrationModel
{
[Required]
[MinLength(8)]
[RegularExpression(@"^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).+$",
ErrorMessage = "Password must contain at least one lowercase letter, one uppercase letter, and one number")]
public string? Password { get; set; }
[Required]
[Compare("Password", ErrorMessage = "Passwords do not match")]
public string? ConfirmPassword { get; set; }
}
}
Custom Validation
<EditForm Model="customModel" OnValidSubmit="HandleSubmit">
<DataAnnotationsValidator />
<CustomValidator @ref="customValidator" />
<NvFieldtext
@bind-Value="customModel.Username"
Label="Username"
For="() => customModel.Username" />
<NvButton Type="submit">Create Account</NvButton>
</EditForm>
@code {
private CustomModel customModel = new();
private CustomValidator customValidator = new();
private async Task HandleSubmit()
{
var result = await customValidator.ValidateAsync();
if (result.IsValid)
{
// Proceed with submission
}
}
public class CustomModel
{
[Required]
public string? Username { get; set; }
}
public class CustomValidator : ComponentBase
{
[CascadingParameter] EditContext? CurrentEditContext { get; set; }
protected override void OnInitialized()
{
if (CurrentEditContext != null)
{
CurrentEditContext.OnValidationRequested += HandleValidationRequested;
}
}
private void HandleValidationRequested(object? sender, ValidationRequestedEventArgs args)
{
// Custom validation logic
var messages = new Dictionary<string, List<string>>();
if (CurrentEditContext?.Model is CustomModel model)
{
if (!string.IsNullOrEmpty(model.Username) && model.Username.Contains("admin"))
{
messages.Add(nameof(model.Username), new List<string> { "Username cannot contain 'admin'" });
}
}
// Add validation messages to context
foreach (var field in messages)
{
CurrentEditContext!.AddValidationMessage(new FieldIdentifier(CurrentEditContext.Model, field.Key), field.Value);
}
}
}
}
Form Submission State Management
Loading States
<EditForm Model="contactModel" OnValidSubmit="HandleSubmit">
<DataAnnotationsValidator />
<NvFieldtext
@bind-Value="contactModel.Name"
Label="Name"
Disabled="isSubmitting"
For="() => contactModel.Name" />
<NvFieldtext
@bind-Value="contactModel.Email"
Label="Email"
Type="TypeEnum.email"
Disabled="isSubmitting"
For="() => contactModel.Email" />
<NvButton Type="submit" Loading="isSubmitting" Disabled="isSubmitting">
@if (isSubmitting) { Sending... } else { Send Message }
</NvButton>
@if (submitMessage != null)
{
<NvAlert Type="@alertType">@submitMessage</NvAlert>
}
</EditForm>
@code {
private ContactModel contactModel = new();
private bool isSubmitting = false;
private string? submitMessage = null;
private string alertType = "info";
private async Task HandleSubmit()
{
isSubmitting = true;
submitMessage = null;
try
{
await Task.Delay(2000); // Simulate API call
submitMessage = "Message sent successfully!";
alertType = "success";
contactModel = new(); // Reset form
}
catch (Exception ex)
{
submitMessage = "Failed to send message. Please try again.";
alertType = "error";
}
finally
{
isSubmitting = false;
}
}
}
Success/Error Handling
<EditForm Model="profileModel" OnValidSubmit="HandleSaveProfile">
<DataAnnotationsValidator />
<NvFieldtext
@bind-Value="profileModel.FirstName"
Label="First Name"
For="() => profileModel.FirstName" />
<NvFieldtext
@bind-Value="profileModel.LastName"
Label="Last Name"
For="() => profileModel.LastName" />
<NvButton Type="submit" Loading="isSaving" Disabled="isSaving">
Save Profile
</NvButton>
</EditForm>
@if (saveResult != null)
{
<NvAlert Type="@saveResult.Type" Dismissible="true" OnDismiss="() => saveResult = null">
@saveResult.Message
</NvAlert>
}
@code {
private ProfileModel profileModel = new();
private bool isSaving = false;
private SaveResult? saveResult = null;
private async Task HandleSaveProfile()
{
isSaving = true;
saveResult = null;
try
{
var result = await SaveProfileAsync(profileModel);
saveResult = new SaveResult("success", "Profile saved successfully!");
}
catch (ValidationException ex)
{
saveResult = new SaveResult("warning", $"Validation error: {ex.Message}");
}
catch (Exception ex)
{
saveResult = new SaveResult("error", "Failed to save profile. Please try again.");
}
finally
{
isSaving = false;
}
}
public record SaveResult(string Type, string Message);
}
Working with Different Field Types
Text Fields
<NvFieldtext
@bind-Value="formData.FirstName"
Label="First Name"
Placeholder="Enter your first name"
Required="true"
For="() => formData.FirstName" />
<NvFieldtext
@bind-Value="formData.Email"
Label="Email Address"
Type="TypeEnum.email"
Placeholder="your.email@example.com"
For="() => formData.Email" />
<NvFieldtext
@bind-Value="formData.Phone"
Label="Phone Number"
Type="TypeEnum.tel"
Placeholder="+1 (555) 123-4567"
For="() => formData.Phone" />
Selection Fields
<NvFieldselect
@bind-Value="formData.Country"
Label="Country"
For="() => formData.Country">
<option value="">Select a country</option>
<option value="us">United States</option>
<option value="ca">Canada</option>
<option value="uk">United Kingdom</option>
</NvFieldselect>
<NvFieldselect
@bind-Value="formData.Department"
Label="Department"
Options="departmentOptions"
For="() => formData.Department" />
@code {
private List<NvFieldselect.Option> departmentOptions = new()
{
new() { Label = "Engineering", Value = "eng" },
new() { Label = "Marketing", Value = "mkt" },
new() { Label = "Sales", Value = "sales" }
};
}
Checkbox and Radio Fields
<NvFieldcheckbox
@bind-Value="formData.AgreeToTerms"
Label="I agree to the terms and conditions"
Required="true"
For="() => formData.AgreeToTerms" />
<div class="space-y-2">
<label class="typo-text-sm-medium">Preferred Contact Method</label>
<NvFieldradio
Name="contactMethod"
Value="email"
@bind-CheckedValue="formData.ContactMethod"
Label="Email" />
<NvFieldradio
Name="contactMethod"
Value="phone"
@bind-CheckedValue="formData.ContactMethod"
Label="Phone" />
<NvFieldradio
Name="contactMethod"
Value="mail"
@bind-CheckedValue="formData.ContactMethod"
Label="Mail" />
</div>
Date and Time Fields
<NvFielddate
@bind-Value="formData.BirthDate"
Label="Date of Birth"
For="() => formData.BirthDate" />
<NvFieldtime
@bind-Value="formData.PreferredTime"
Label="Preferred Contact Time"
For="() => formData.PreferredTime" />
<NvFielddaterange
@bind-Value="formData.VacationPeriod"
Label="Vacation Period"
For="() => formData.VacationPeriod" />
Number and Slider Fields
<NvFieldnumber
@bind-Value="formData.Age"
Label="Age"
Min="18"
Max="120"
For="() => formData.Age" />
<NvFieldslider
@bind-Value="formData.Satisfaction"
Label="Satisfaction Level"
Min="1"
Max="10"
For="() => formData.Satisfaction" />
Advanced Form Patterns
Multi-Step Forms
@if (currentStep == 1)
{
<EditForm Model="step1Model" OnValidSubmit="GoToStep2">
<DataAnnotationsValidator />
<NvFieldtext
@bind-Value="step1Model.FirstName"
Label="First Name"
For="() => step1Model.FirstName" />
<NvFieldtext
@bind-Value="step1Model.LastName"
Label="Last Name"
For="() => step1Model.LastName" />
<NvButton Type="submit">Next</NvButton>
</EditForm>
}
else if (currentStep == 2)
{
<EditForm Model="step2Model" OnValidSubmit="HandleFinalSubmit">
<DataAnnotationsValidator />
<NvFieldtext
@bind-Value="step2Model.Email"
Label="Email"
Type="TypeEnum.email"
For="() => step2Model.Email" />
<NvFieldtext
@bind-Value="step2Model.Phone"
Label="Phone"
Type="TypeEnum.tel"
For="() => step2Model.Phone" />
<NvButton @onclick="GoToStep1">Back</NvButton>
<NvButton Type="submit" Loading="isSubmitting">Submit</NvButton>
</EditForm>
}
@code {
private int currentStep = 1;
private Step1Model step1Model = new();
private Step2Model step2Model = new();
private bool isSubmitting = false;
private void GoToStep2()
{
currentStep = 2;
}
private void GoToStep1()
{
currentStep = 1;
}
private async Task HandleFinalSubmit()
{
isSubmitting = true;
try
{
// Combine data and submit
var completeModel = new CompleteModel
{
FirstName = step1Model.FirstName,
LastName = step1Model.LastName,
Email = step2Model.Email,
Phone = step2Model.Phone
};
await SubmitCompleteForm(completeModel);
}
finally
{
isSubmitting = false;
}
}
}
Dynamic Forms
<EditForm Model="dynamicModel" OnValidSubmit="HandleSubmit">
<DataAnnotationsValidator />
@foreach (var field in dynamicFields)
{
<NvFieldtext
@bind-Value="field.Value"
Label="field.Label"
Type="field.Type"
Required="field.Required"
Description="field.Description" />
}
<NvButton Type="submit">Submit</NvButton>
</EditForm>
@code {
private DynamicModel dynamicModel = new();
private List<DynamicField> dynamicFields = new();
protected override void OnInitialized()
{
dynamicFields = new List<DynamicField>
{
new() { Label = "Name", Type = TypeEnum.text, Required = true },
new() { Label = "Email", Type = TypeEnum.email, Required = true },
new() { Label = "Phone", Type = TypeEnum.tel, Required = false, Description = "Optional" }
};
}
public class DynamicField
{
public string Label { get; set; } = "";
public TypeEnum Type { get; set; }
public bool Required { get; set; }
public string? Description { get; set; }
public string Value { get; set; } = "";
}
}
Form Arrays and Collections
<EditForm Model="formModel" OnValidSubmit="HandleSubmit">
<DataAnnotationsValidator />
@for (int i = 0; i < formModel.Addresses.Count; i++)
{
var index = i;
<div class="address-section">
<h4>Address @(index + 1)</h4>
<NvFieldtext
@bind-Value="formModel.Addresses[index].Street"
Label="Street Address"
For="() => formModel.Addresses[index].Street" />
<NvFieldtext
@bind-Value="formModel.Addresses[index].City"
Label="City"
For="() => formModel.Addresses[index].City" />
<NvButton @onclick="() => RemoveAddress(index)">Remove</NvButton>
</div>
}
<NvButton @onclick="AddAddress">Add Another Address</NvButton>
<NvButton Type="submit">Submit</NvButton>
</EditForm>
@code {
private FormModel formModel = new() { Addresses = new List<AddressModel>() };
private void AddAddress()
{
formModel.Addresses.Add(new AddressModel());
}
private void RemoveAddress(int index)
{
if (formModel.Addresses.Count > 1)
{
formModel.Addresses.RemoveAt(index);
}
}
public class FormModel
{
public List<AddressModel> Addresses { get; set; } = new();
}
public class AddressModel
{
[Required]
public string? Street { get; set; }
[Required]
public string? City { get; set; }
}
}
Best Practices
DO: Use Proper Validation
Always use the For parameter with EditForm for automatic validation integration:
<!-- Good: Proper validation integration -->
<EditForm Model="model">
<DataAnnotationsValidator />
<NvFieldtext @bind-Value="model.Email" For="() => model.Email" />
</EditForm>
DO: Handle Form States
Provide appropriate feedback for all form states:
<!-- Good: Comprehensive state handling -->
<NvButton Type="submit" Loading="isSubmitting" Disabled="isSubmitting">
@if (isSubmitting) { Processing... } else { Submit }
</NvButton>
@if (errorMessage != null)
{
<NvAlert Type="error">@errorMessage</NvAlert>
}
DO: Use Appropriate Field Types
Choose the right field type for better UX:
<!-- Good: Semantic field types -->
<NvFieldtext Type="TypeEnum.email" ... />
<NvFieldtext Type="TypeEnum.tel" ... />
<NvFielddate ... />
DON'T: Mix Validation Approaches
Avoid mixing manual validation with automatic validation:
<!-- Bad: Conflicting validation approaches -->
<NvFieldtext
@bind-Value="email"
Error="true"
ErrorDescription="Invalid email"
For="() => model.Email" /> <!-- This will override manual error -->
DON'T: Forget Form Reset
Always reset forms after successful submission:
<!-- Good: Form reset after success -->
private async Task HandleSubmit()
{
try
{
await SubmitForm(model);
model = new Model(); // Reset form
successMessage = "Submitted successfully!";
}
catch
{
errorMessage = "Submission failed.";
}
}
DON'T: Ignore Accessibility
Ensure proper labeling and keyboard navigation:
<!-- Good: Proper accessibility -->
<NvFieldtext
Label="Email Address"
InputId="email-input"
Autocomplete="AutocompleteEnum.email" ... />
Common Form Patterns
User Registration
<EditForm Model="registrationModel" OnValidSubmit="HandleRegistration">
<DataAnnotationsValidator />
<div class="grid grid-cols-2 gap-4">
<NvFieldtext
@bind-Value="registrationModel.FirstName"
Label="First Name"
For="() => registrationModel.FirstName" />
<NvFieldtext
@bind-Value="registrationModel.LastName"
Label="Last Name"
For="() => registrationModel.LastName" />
</div>
<NvFieldtext
@bind-Value="registrationModel.Email"
Label="Email Address"
Type="TypeEnum.email"
For="() => registrationModel.Email" />
<NvFieldtext
@bind-Value="registrationModel.Password"
Label="Password"
Type="TypeEnum.password"
For="() => registrationModel.Password" />
<NvFieldcheckbox
@bind-Value="registrationModel.AgreeToTerms"
Label="I agree to the Terms and Conditions"
For="() => registrationModel.AgreeToTerms" />
<NvButton Type="submit" Loading="isRegistering" Fluid="true">
Create Account
</NvButton>
</EditForm>
Contact Form
<EditForm Model="contactModel" OnValidSubmit="HandleContactSubmit">
<DataAnnotationsValidator />
<div class="grid grid-cols-2 gap-4">
<NvFieldtext
@bind-Value="contactModel.FirstName"
Label="First Name"
For="() => contactModel.FirstName" />
<NvFieldtext
@bind-Value="contactModel.LastName"
Label="Last Name"
For="() => contactModel.LastName" />
</div>
<NvFieldtext
@bind-Value="contactModel.Email"
Label="Email Address"
Type="TypeEnum.email"
For="() => contactModel.Email" />
<NvFieldtext
@bind-Value="contactModel.Subject"
Label="Subject"
For="() => contactModel.Subject" />
<NvFieldtextarea
@bind-Value="contactModel.Message"
Label="Message"
Rows="5"
For="() => contactModel.Message" />
<NvButton Type="submit" Loading="isSubmitting">
Send Message
</NvButton>
</EditForm>
Search Form
<EditForm Model="searchModel" OnValidSubmit="HandleSearch">
<DataAnnotationsValidator />
<div class="flex gap-4">
<NvFieldtext
@bind-Value="searchModel.Query"
Label="Search"
Placeholder="Enter search terms..."
Fluid="true"
For="() => searchModel.Query" />
<NvFieldselect
@bind-Value="searchModel.Category"
Label="Category"
Options="categoryOptions"
For="() => searchModel.Category" />
<NvButton Type="submit" Loading="isSearching">
Search
</NvButton>
</div>
</EditForm>
@if (searchResults.Any())
{
<div class="mt-4">
<h3>Search Results</h3>
@foreach (var result in searchResults)
{
<div class="result-item">@result</div>
}
</div>
}
Troubleshooting
Validation Not Working
Ensure the For parameter is set correctly:
<!-- Ensure For parameter matches the model property -->
<NvFieldtext
@bind-Value="model.Email"
For="() => model.Email" /> <!-- Correct -->
Binding Not Updating
Check that the model property has a setter:
public class Model
{
public string Email { get; set; } = ""; // Must have setter
}
Form Not Submitting
Ensure OnValidSubmit is used instead of @onclick:
<!-- Correct -->
<EditForm OnValidSubmit="HandleSubmit">
<NvButton Type="submit">Submit</NvButton>
</EditForm>
<!-- Incorrect -->
<EditForm>
<NvButton @onclick="HandleSubmit">Submit</NvButton>
</EditForm>
Resources
Blazor Documentation
This guide provides the foundation for building robust, accessible forms in Blazor applications using Nova's design system. The patterns demonstrated here ensure consistent user experience and proper validation across your application.