TL;DR: Blazor forms are essential for modern web apps, but building them with dynamic layouts and validation can be challenging. This guide shows how to master Blazor forms using best practices and reusable patterns for a seamless developer experience.
Creating advanced Blazor forms can be challenging, especially when working with dynamic fields, validation, and layout customization. In this blog post, we’ll demonstrate how to leverage the Blazor DataForm component and additional form controls to build a sophisticated user profile form. Detailed examples showcase field grouping, conditional rendering, custom validation, and a developer-friendly tone.
Whether building a user profile form or a multi-step wizard, this guide will help you master Blazor advanced forms with practical examples and reusable patterns.
Advanced forms are vital in enterprise apps, but their complexity makes them challenging to build. The Syncfusion® Blazor DataForm component simplifies this with:
These features make it a top choice for .NET developers. For more details, check out the Syncfusion® DataForm documentation.
This guide walks through creating an advanced user profile form featuring:
Before getting started, make sure that the following prerequisites are installed:
Create a new Blazor web app application using Visual Studio, install Syncfusion® Blazor Packages, and configure the style and script reference as outlined in the document.
Let’s get started with a step-by-step guide.
Create a C# class for the user profile, including data annotations for validation and a custom attribute for email uniqueness.
using System.ComponentModel.DataAnnotations;
public class UserProfile
{
[Required(ErrorMessage = "First name is required.")]
[StringLength(50, ErrorMessage = "First name cannot exceed 50 characters.")]
public string FirstName { get; set; }
[StringLength(50, ErrorMessage = "Last name cannot exceed 50 characters.")]
public string LastName { get; set; }
[Required(ErrorMessage = "Email is required.")]
[EmailAddress(ErrorMessage = "Invalid email address.")]
[UniqueEmail]
public string Email { get; set; }
[Required(ErrorMessage = "Date of birth is required.")]
[DataType(DataType.Date)]
public DateTime? DateOfBirth { get; set; }
[Required(ErrorMessage = "Address Line 1 is required.")]
[StringLength(100, ErrorMessage = "Address Line 1 cannot exceed 100 characters.")]
public string AddressLine1 { get; set; }
[StringLength(100, ErrorMessage = "Address Line 2 cannot exceed 100 characters.")]
public string AddressLine2 { get; set; } // Optional field
[Required(ErrorMessage = "City is required.")]
[StringLength(50, ErrorMessage = "City cannot exceed 50 characters.")]
public string City { get; set; }
[Required(ErrorMessage = "State is required.")]
[StringLength(50, ErrorMessage = "State cannot exceed 50 characters.")]
public string State { get; set; }
[Required(ErrorMessage = "Zip code is required.")]
[RegularExpression(@"^\d{5}(-\d{4})?$", ErrorMessage = "Invalid zip code format.")]
public string ZipCode { get; set; }
public bool ReceiveNewsletter { get; set; }
[Required(ErrorMessage = "Preferred language is required.")]
public string PreferredLanguage { get; set; }
[StringLength(20, ErrorMessage = "Newsletter frequency cannot exceed 20 characters.")]
public string NewsletterFrequency { get; set; } // Optional, shown conditionally
}
public class UniqueEmailAttribute : ValidationAttribute
{
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var email = value as string;
// Placeholder logic: assume "taken@example.com" is already used
if (email == "taken@example.com")
{
return new ValidationResult("Email already exists.");
}
return ValidationResult.Success;
}
} Add the Syncfusion® DataForm to your Blazor page and bind it to the UserProfile model.
@using Syncfusion.Blazor.DataForm
@using System.ComponentModel.DataAnnotations
<SfDataForm ID="UserProfileForm" Model="@userProfile">
<FormValidator>
<DataAnnotationsValidator></DataAnnotationsValidator>
</FormValidator>
<FormItems>
<FormAutoGenerateItems />
</FormItems>
</SfDataForm>
@code {
private UserProfile userProfile = new UserProfile();
} This auto-generates fields based on the model, with customization to follow.
Organize fields into logical groups using FormGroup for a clean UI.
<SfDataForm ID="UserProfileForm"
Model="@userProfile"
ValidationDisplayMode="FormValidationDisplay.Tooltip">
<FormValidator>
<DataAnnotationsValidator></DataAnnotationsValidator>
</FormValidator>
<FormItems>
<FormGroup LabelText="Personal Information">
<FormItem Field="@nameof(UserProfile.FirstName)" />
<FormItem Field="@nameof(UserProfile.LastName)" />
<FormItem Field="@nameof(UserProfile.Email)" />
<FormItem Field="@nameof(UserProfile.DateOfBirth)" />
</FormGroup>
<FormGroup LabelText="Address Details">
<FormItem Field="@nameof(UserProfile.AddressLine1)" />
<FormItem Field="@nameof(UserProfile.AddressLine2)" />
<FormItem Field="@nameof(UserProfile.City)" />
<FormItem Field="@nameof(UserProfile.State)" />
<FormItem Field="@nameof(UserProfile.ZipCode)" />
</FormGroup>
<FormGroup LabelText="Preferences">
<FormItem Field="@nameof(UserProfile.ReceiveNewsletter)" />
<FormItem Field="@nameof(UserProfile.PreferredLanguage)" />
<FormItem Field="@nameof(UserProfile.NewsletterFrequency)" />
</FormGroup>
</FormItems>
</SfDataForm> Setting ValidationDisplayMode="FormValidationDisplay.Tooltip to show validation errors as tooltips.
Improve the form with selection and date-picking options for better usability.
@using Syncfusion.Blazor.DropDowns
@using Syncfusion.Blazor.Calendars
<SfDataForm ID="UserProfileForm"
Model="@userProfile"
ValidationDisplayMode="FormValidationDisplay.Tooltip">
<FormValidator>
<DataAnnotationsValidator></DataAnnotationsValidator>
</FormValidator>
<FormItems>
<FormGroup LabelText="Personal Information">
<FormItem Field="@nameof(UserProfile.FirstName)" />
<FormItem Field="@nameof(UserProfile.LastName)" />
<FormItem Field="@nameof(UserProfile.Email)" />
<FormItem Field="@nameof(UserProfile.DateOfBirth)">
<Template>
<SfDatePicker ID="@nameof(UserProfile.DateOfBirth)"
TValue="DateTime?"
@bind-Value="@userProfile.DateOfBirth" />
</Template>
</FormItem>
</FormGroup>
<FormGroup LabelText="Address Details">
<FormItem Field="@nameof(UserProfile.AddressLine1)" />
<FormItem Field="@nameof(UserProfile.AddressLine2)" />
<FormItem Field="@nameof(UserProfile.City)" />
<FormItem Field="@nameof(UserProfile.State)" />
<FormItem Field="@nameof(UserProfile.ZipCode)" />
</FormGroup>
<FormGroup LabelText="Preferences">
<FormItem Field="@nameof(UserProfile.ReceiveNewsletter)" />
<FormItem Field="@nameof(UserProfile.PreferredLanguage)">
<Template>
<SfDropDownList Enabled="@userProfile.ReceiveNewsletter"
ID="@nameof(UserProfile.PreferredLanguage)"
TItem="string"
TValue="string"
DataSource="@languages"
@bind-Value="@userProfile.PreferredLanguage">
<DropDownListFieldSettings Text="Text" Value="Value" />
</SfDropDownList>
</Template>
</FormItem>
<FormItem IsEnabled="@userProfile.ReceiveNewsletter"
Field="@nameof(UserProfile.NewsletterFrequency)" />
</FormGroup>
</FormItems>
</SfDataForm>
@code {
private UserProfile userProfile = new UserProfile();
private List<string> languages = new List<string> { "English", "Spanish", "French" };
} Add a submit button and use IsValid() to check form validity.
<SfDataForm @ref="dataForm"
ID="UserProfileForm"
Model="@userProfile"
ValidationDisplayMode="FormValidationDisplay.Tooltip">
<FormValidator>
<DataAnnotationsValidator></DataAnnotationsValidator>
</FormValidator>
<FormItems>
<!-- Form items as above -->
</FormItems>
<FormButtons>
<SfButton IsPrimary="true" OnClick="@SubmitForm">Submit</SfButton>
</FormButtons>
</SfDataForm>
@code {
private SfDataForm dataForm;
private UserProfile userProfile = new UserProfile();
private List<string> languages = new List<string> { "English", "Spanish", "French" };
private void SubmitForm()
{
bool isValid = dataForm.IsValid();
if (isValid)
{
// Process form data (e.g., save to API)
Console.WriteLine("Form submitted successfully!");
}
}
} Use ValidationSummary to display all validation errors in one place, complementing the tooltip display.
<SfDataForm @ref="dataForm"
ID="UserProfileForm"
Model="@userProfile"
ValidationDisplayMode="FormValidationDisplay.Tooltip">
<FormValidator>
<DataAnnotationsValidator></DataAnnotationsValidator>
<ValidationSummary />
</FormValidator>
<FormItems>
<!-- Form items as above -->
</FormItems>
<FormButtons>
<SfButton IsPrimary="true" OnClick="@SubmitForm">Submit</SfButton>
</FormButtons>
</SfDataForm> For the complete code and styling details, please refer to the GitHub repository. It contains all the source files and configurations used in this project.
Advanced forms in Blazor don’t have to be complex. With the right approach to validation, layout, and conditional logic, you can build scalable and user-friendly forms that elevate your application. The Syncfusion® Blazor DataForm component empowers .NET developers to create advanced, user-friendly forms with ease. By leveraging data annotations, custom validation, conditional fields, and Syncfusion’s rich component library, you can build robust forms for any Blazor app.
Explore Syncfusion® Blazor DataForm components on Syncfusion’s official documentation. Start building your advanced forms today and transform your Blazor applications effortlessly.
If you’re already a Syncfusion® user, you can download the latest version of Essential Studio® from the license and downloads page. New to Syncfusion® Start your journey with a 30-day free trial and explore over 1,900 UI components, including powerful charting tools for Blazor.
If you need assistance, please do not hesitate to contact us via our support forum, support portal, or feedback portal. We are always eager to help you!