Form Validation in Dropdown List

18 Jan 20232 minutes to read

This demonstrates the creation of a form that includes a dropdown list, allowing the user to select an option from a list of items. The form also includes validation, which verifies that all required fields are filled out before the form can be submitted.

The DropDownList component can be used inside an EditForm to create a form that includes a list for selecting an option. The EditForm component validates all data annotation rules using the DataAnnotationsValidator component.

When the DropDownList input is valid, the form is ready to be submitted. If the input is invalid, an error message will be displayed until a valid value is chosen.

  • The EditForm component wraps the entire form, has the Model attribute set to the model variable of type Countries, and triggers the handleSubmit() method when the form is submitted.
  • The DataAnnotationsValidator component enables validation based on the Data Annotations attributes applied on the model properties.
  • The ValidationSummary component displays a summary of all validation errors on the form.
  • The ValidationMessage component displays a validation error message for the Name property of the model variable.
  • The submit button submits the form and triggers the handleSubmit() method when clicked.
  • CSHTML
  • @using Syncfusion.Blazor.DropDowns; 
    @using System.ComponentModel.DataAnnotations; 
     
    <EditForm Model="@model" OnValidSubmit="handleSubmit"> 
        <DataAnnotationsValidator></DataAnnotationsValidator> 
        <ValidationSummary></ValidationSummary> 
        <SfDropDownList TValue="string" TItem="Countries" Placeholder="e.g. Australia" Width="300px" @bind-Value="@model.Name" DataSource="@Country"> 
            <DropDownListFieldSettings Value="Name"></DropDownListFieldSettings> 
        </SfDropDownList> 
        <ValidationMessage For="()=>model.Name"></ValidationMessage> 
        <button type="submit">submit</button> 
    </EditForm> 
     
     
    @code {  
        private Countries model = new Countries(); 
        public class Countries 
        { 
            [Required] 
            public string Name { get; set; } 
     
            public string Code { get; set; } 
        } 
     
        List<Countries> Country = new List<Countries> 
        { 
            new Countries() { Name = "Australia", Code = "AU" }, 
            new Countries() { Name = "Bermuda", Code = "BM" }, 
            new Countries() { Name = "Canada", Code = "CA" }, 
            new Countries() { Name = "Cameroon", Code = "CM" }, 
        }; 
        private void handleSubmit() 
        { 
     
        } 
    }

    Blazor DropdownList inside editform