Spice up your Blazor EditForm with Syncfusion Blazor Components | Syncfusion Blogs
Live Chat Icon For mobile
Live Chat Icon
Popular Categories.NET  (173).NET Core  (29).NET MAUI  (203)Angular  (107)ASP.NET  (51)ASP.NET Core  (82)ASP.NET MVC  (89)Azure  (40)Black Friday Deal  (1)Blazor  (211)BoldSign  (13)DocIO  (24)Essential JS 2  (106)Essential Studio  (200)File Formats  (65)Flutter  (132)JavaScript  (219)Microsoft  (118)PDF  (81)Python  (1)React  (98)Streamlit  (1)Succinctly series  (131)Syncfusion  (897)TypeScript  (33)Uno Platform  (3)UWP  (4)Vue  (45)Webinar  (50)Windows Forms  (61)WinUI  (68)WPF  (157)Xamarin  (161)XlsIO  (35)Other CategoriesBarcode  (5)BI  (29)Bold BI  (8)Bold Reports  (2)Build conference  (8)Business intelligence  (55)Button  (4)C#  (146)Chart  (127)Cloud  (15)Company  (443)Dashboard  (8)Data Science  (3)Data Validation  (8)DataGrid  (63)Development  (618)Doc  (8)DockingManager  (1)eBook  (99)Enterprise  (22)Entity Framework  (5)Essential Tools  (14)Excel  (39)Extensions  (22)File Manager  (6)Gantt  (18)Gauge  (12)Git  (5)Grid  (31)HTML  (13)Installer  (2)Knockout  (2)Language  (1)LINQPad  (1)Linux  (2)M-Commerce  (1)Metro Studio  (11)Mobile  (501)Mobile MVC  (9)OLAP server  (1)Open source  (1)Orubase  (12)Partners  (21)PDF viewer  (42)Performance  (12)PHP  (2)PivotGrid  (4)Predictive Analytics  (6)Report Server  (3)Reporting  (10)Reporting / Back Office  (11)Rich Text Editor  (12)Road Map  (12)Scheduler  (52)Security  (3)SfDataGrid  (9)Silverlight  (21)Sneak Peek  (31)Solution Services  (4)Spreadsheet  (11)SQL  (10)Stock Chart  (1)Surface  (4)Tablets  (5)Theme  (12)Tips and Tricks  (112)UI  (381)Uncategorized  (68)Unix  (2)User interface  (68)Visual State Manager  (2)Visual Studio  (31)Visual Studio Code  (17)Web  (582)What's new  (323)Windows 8  (19)Windows App  (2)Windows Phone  (15)Windows Phone 7  (9)WinRT  (26)
How to Create an EditForm for Employee Details with Syncfusion Blazor Components

Spice up your Blazor EditForm with Syncfusion Blazor Components

In this blog post, we will look at the steps to create an EditForm for collecting employees’ details with data annotation validation by using Syncfusion Blazor components (Checkbox, Radio Button, etc.). You will also learn about configuring and displaying validation messages using data annotation by extending the sample with simple code examples.

What is form-validation?

Validation is very important for any application. Form validation is the process of ensuring that the provided data is in the right format in form components before submitting data to the server.

If we failed to enter our data in the correct format, we will get validation messages such as:

  • “This field is required.”—On not filling in a mandatory field.
  • “The data in the phone number field is not a valid phone number.”—If there is a mismatch in the format of the phone number.
  • “The data in the email field is not a valid email address.”—If there is a violation in the email ID format.
  • “The field range should be 0 to 20.”—If entered number exceeds the acceptable range. Both minimum and maximum values in this message are customizable.

Blazor components provide form validation using data annotation. It can add one or more attributes to a model’s property. There are many built-in data annotation attributes provided by the .NET Core framework and you can also build your own data validation attribute (custom attribute).

Let’s see how easily you can configure Syncfusion Blazor components in EditForm with data validation.

Prerequisites

Create a Blazor server application

  1. Create a Blazor server app and add the required model classes.
  2. Then create a new model class file inside the Data folder with the name EmployeeDetails.
  3. In this class file, add the class definitions for the Countries and Cities classes with the required properties and methods to generate appropriate data for Dropdown List, which you can reference from this GitHub

Add Data annotation attribute in Form model

The validation attributes specify the validation rules for the model properties. The EmployeeDetails model has various properties with built-in validation data annotation attributes like Required, EmailAddress, Phone, and Range.

Refer to the following code example.

public class EmployeeDetails
    {
        [Required]
        public string FirstName { get; set; }
        public string LastName { get; set; }
        [Required]
        [DataType(DataType.EmailAddress)]
        [EmailAddress]
        public string Email { get; set; }
        public bool Gender { get; set; }
        [Required]
        [DataType(DataType.PhoneNumber)]
        [Phone]
        public string PhoneNumber { get; set; }
        [Required]
        public DateTime? DOB { get; set; }
        [Required]
        public string Country { get; set; }
        [Required]
        public string City { get; set; }
        [Required]
        public string Address { get; set; }
        [Required]
        [Range(0, 20, ErrorMessage = "The Experience range should be 0 to 20")]
        public decimal? TotalExperience { get; set; }
    }

Design employee form

After creating the required model classes, access them inside the index.razor component under the pages folder, where we are going to design the EditForm with Syncfusion form components.

  1. Add the following code example to include the EditForm component. It creates an EditContext that tracks the fields modified in the form and tracks the validation messages.
    <EditForm OnValidSubmit="@Submit">
    </EditForm>
    
  2. Now, we create the EmployeeDetails class instance for the EditForm model binding.
    <EditForm Model="@employeeDetails"OnValidSubmit="@Submit">
    </EditForm>
    
    @code{
    
    EmployeeDetails;
    protected override void OnInitialized()
        {
            employeeDetails = new EmployeeDetails();
        }
    }
    
  3. Then, add the DataAnnotationsValidator component in the EditForm to validate the input fields.
    <EditForm Model="@employeeDetails" OnValidSubmit="@Submit">
        <DataAnnotationsValidator/>
    </EditForm>
    
  4. Now, we are going to design the employee detail entry form using Syncfusion form components and include validation messages like in the following.
    <EditForm Model="@employeeDetails" OnValidSubmit="@Submit">
        <DataAnnotationsValidator/>
        <div class="form-row">
            <div class="form-group col-md-6">
                <label class="col-form-label">First Name :</label>
                <SfTextBox @bind-Value="@employeeDetails.FirstName"></SfTextBox>
                <ValidationMessage For="@(() => employeeDetails.FirstName)"></ValidationMessage>
            </div>
            <div class="form-group col-md-6">
                <label class="col-form-label">Last Name :</label>
                <SfTextBox @bind-Value="@employeeDetails.LastName"></SfTextBox>
                <ValidationMessage For="@(() => employeeDetails.LastName)"></ValidationMessage>
            </div>
        </div>
        <div class="form-row">
            <div class="form-group col-md-6">
                <label class="col-form-label">Email ID :</label>
                <SfTextBox @bind-Value="@employeeDetails.Email"></SfTextBox>
                <ValidationMessage For="@(() => employeeDetails.Email)"></ValidationMessage>
            </div>
            <div class="form-group col-md-6">
                <label class="col-form-label">Phone Number :</label>
                <SfTextBox @bind-Value="@employeeDetails.PhoneNumber"></SfTextBox>
                <ValidationMessage For="@(() => employeeDetails.PhoneNumber)"></ValidationMessage>
            </div>
        </div>
    
        <div class="form-row">
            <div class="form-group col-md-6">
                <label class="col-form-label">Date Of Birth :</label>
                <SfDatePicker @bind-Value="@employeeDetails.DOB" Max=DateTime.Now></SfDatePicker>
                <ValidationMessage For="@(() => employeeDetails.DOB)"></ValidationMessage>
            </div>
            <div class="form-group col-md-6">
                <label class="col-form-label">Total Experience :</label>
                <SfNumericTextBox @bind-Value="@employeeDetails.TotalExperience"></SfNumericTextBox>
                <ValidationMessage For="@(() => employeeDetails.TotalExperience)"></ValidationMessage>
            </div>
        </div>
        <div class="form-row">
            <div class="form-group col-md-6">
                <label class="col-form-label">Address :</label>
                <SfTextBox Multiline=true @bind-Value="@employeeDetails.Address"></SfTextBox>
                <ValidationMessage For="@(() => employeeDetails.Address)"></ValidationMessage>
            </div>
            <div class="form-group col-md-3">
                <label class="col-form-label">Gender :</label>
                <div>
                    <SfRadioButton Label="Male" Name="Gender" Value="male" @bind-Checked="@employeeDetails.Gender"></SfRadioButton>
                    <SfRadioButton Label="Female" Name="Gender" Value="female"></SfRadioButton>
                    <ValidationMessage For="@(() => employeeDetails.Gender)" />
                </div>
            </div>
    
        </div>
        <div class="form-row">
            <div class="form-group col-md-6">
                <label class="col-form-label">Country :</label>
                <SfComboBox TValue="string" TItem="Countries" @bind-Value="@employeeDetails.Country" DataSource="@countries">
                    <ComboBoxFieldSettings Text="Name" Value="Code"></ComboBoxFieldSettings>
                    <ComboBoxEvents TValue="string" ValueChange="ChangeCountry"></ComboBoxEvents>
                </SfComboBox>
                <ValidationMessage For="@(() => employeeDetails.Country)"></ValidationMessage>
            </div>
            <div class="form-group col-md-6">
                <label class="col-form-label">City :</label>
                <SfDropDownList Enabled="@enableCityDropDown" TValue="string" TItem="Cities" @bind-Value="@employeeDetails.City" Query="@CityQuery" DataSource="@cities">
                    <DropDownListFieldSettings Text="Name" Value="Code"></DropDownListFieldSettings>
                </SfDropDownList>
                <ValidationMessage For="@(() => employeeDetails.City)"></ValidationMessage>
            </div>
        </div>
        <div class="form-group">
            <button type="submit" class="btn btn-primary">Save</button>
        </div>
    </EditForm>
    

Now, the Blazor engine will validate the inputs using data annotation and list all the form validations on the submit button being clicked. Look at the following screenshot to see how a validation message will be displayed in the Employee Details Form by executing the previous code example.
EditForm in Blazor using Syncfusion components

Validation summary

We can also create a ValidationSummary that would display all the errors for a specific place on clicking the submit button.

<EditForm Model="@employeeDetails" OnValidSubmit="@Submit">
    <DataAnnotationsValidator/>
    <ValidationSummary />
    <div class="form-group">
        <SfButton Type="submit" IsPrimary=true>Save</SfButton>
    </div>
</EditForm>

Conclusion

I hope this blog post helped you understand how easily you can create the EditForm with data annotation. Now, you can create your own forms with validations using Syncfusion Blazor components with minimal lines of reusable code. You can download the complete source code of this example from this GitHub repository.

Try our 65+ high-performance Blazor components by downloading a free 30-day trial or our NuGet package. Have a look at our online examples and documentation to explore other available features.

If you have any questions or some other feedback about EditForm, please let us know in the comments section below. You can also contact us through our feedback portal, support forum or Direct-Trac. We are always happy to assist you!

Tags:

Share this post:

Comments (6)

Bernardo Mondragon Brozon
Bernardo Mondragon Brozon

Do you know how to set default values into the form?

Or do it when you initialize the new class variable, like in the OnInitialized event. I like doing it there as I can business logic to it, rather than in the class definition.

Hello Bernardo,
Yes, you can add a default value in the model class.

[Required]
public DateTime? DOB { get; set; } = DateTime.Now;

Regards,
Saravanan G

Hi. How can one add pagination to an editform when you have many form components in ?

so you can have sections of the form components on multiple pages where they can be navigated to and from using a next and previous button on the same @page and

which all data in the form components will be saved with the OnValidSubmit button

Note that bootstrap 5 does not include form-group, form-row etc. anymore.
https://getbootstrap.com/docs/5.0/migration/#forms
“Breaking change: Dropped form-specific layout classes for our grid system. Use our grid and utilities instead of .form-group, .form-row, or .form-inline.”

Hello Greg,

Thank you for your update, In the GitHub sample we have used Bootstrap v4.3.1 version CSS if you have upgraded the bootstrap 5 please do the respective breaking changes in your end.

Regards,
Saravanan G

Comments are closed.

Popular Now

Be the first to get updates

Subscribe RSS feed

Be the first to get updates

Subscribe RSS feed