DEV Community

Cover image for Blazor Forms Made Easy: Advanced DataForm Layouts, Smart Validation & UX Tips
Zahra Sandra Nasaka for Syncfusion, Inc.

Posted on • Originally published at syncfusion.com on

Blazor Forms Made Easy: Advanced DataForm Layouts, Smart Validation & UX Tips

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.

Why Syncfusion® Blazor DataForm?

Advanced forms are vital in enterprise apps, but their complexity makes them challenging to build. The Syncfusion® Blazor DataForm component simplifies this with:

  • Automatic field generation: Generates form fields from your model, reducing boilerplate code.
  • Customizable layouts: Organize fields into groups for a polished UI.
  • Robust validation: Supports standard and custom validation for data integrity.
  • Component integration: Works seamlessly with Syncfusion® controls like DropDownList and DatePicker.

These features make it a top choice for .NET developers. For more details, check out the Syncfusion® DataForm documentation.

Key features of advanced Blazor forms

This guide walks through creating an advanced user profile form featuring:

  • Multiple sections: Personal information, address details, and preferences.
  • Conditional fields: Show fields like newsletter frequency based on user input.
  • Custom validation: Ensure email uniqueness with a custom validation attribute.
  • Enhanced UI: Integrate Syncfusion’s DropDownList and DatePicker for a better user experience.

Prerequisites

Before getting started, make sure that the following prerequisites are installed:

Integrating Syncfusion® Blazor DataForm

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 getting started documentation.

Let’s get started with a step-by-step guide.

Step 1: Define the data model

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;
    }
}
Enter fullscreen mode Exit fullscreen mode

Step 2: Set up the DataForm component

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();
}
Enter fullscreen mode Exit fullscreen mode

This auto-generates fields based on the model, with customization to follow.

Step 3: Customize layout with form groups

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>
Enter fullscreen mode Exit fullscreen mode

Setting ValidationDisplayMode="FormValidationDisplay.Tooltip to show validation errors as tooltips.

Step 4: Integrate enhanced controls

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" };
}
Enter fullscreen mode Exit fullscreen mode

Step 5: Handle form submission

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!");
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Step 6: Enhance validation feedback

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>
Enter fullscreen mode Exit fullscreen mode

Advanced Blazor Data Form


Advanced Blazor Data Form

Best practices for Syncfusion® DataForm

  • Maximize data annotations: Use [Required], [StringLength], [RegularExpression], and custom attributes for robust validation.
  • Logical grouping: Use FormGroup to organize fields intuitively.
  • Enhance UX: Integrate Syncfusion® controls like SfDropDownList and SfDatePicker.
  • Test conditional logic: Verify that dynamic fields update correctly.
  • Customize validation feedback: Combine ValidationDisplayMode and ValidationSummary for clear error messages.
  • Optimize Large Forms: Consider multi-step forms for performance.

GitHub reference

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.

Conclusion

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!

Related Blogs

This article was originally published at Syncfusion.com.

Top comments (0)