How do I do server-side form validation?

Platform: Blazor| Category: Forms and validation

To carry out form validation in a Blazor server-side application, use data annotations to enable validation for the forms. Also, include <DataAnnotationsValidator  /> and <ValidationSummary /> in the forms.

Refer to the following code sample.

@page "/employeedetails"
@using System.ComponentModel.DataAnnotations;

<EditForm Model="@_employee" OnValidSubmit="HandleValidSubmit">
<DataAnnotationsValidator />
 <ValidationSummary />
    <InputText id="name" @bind-Value="_employee.Name" />
    <button type="submit">Submit</button>
</EditForm>

@code {
    public class Employee
    {
        [Required]
        [StringLength(10, ErrorMessage = "Name is too long.")]
        public string Name { get; set; }
    }

    private Employee _employee = new Employee();

    private void HandleValidSubmit()
    {
         Console.WriteLine("OnValidSubmit");
    }
}

Share with

Related FAQs

Couldn't find the FAQs you're looking for?

Please submit your question and answer.