What is the purpose of a display name in built-in form components?
The DisplayName property, which is set for built-in form components, help maintain an alternate name. When the component’s input value is incorrect due to form validation, this alternate name is displayed in the error message. The DisplayName property is supported by the following built-in components. InputCheckbox InputDate InputNumber InputRadioGroup InputSelect InputText InputTextArea Please refer to the code example below. [Index.razor] View Sample in GitHub
How to add custom validation in Blazor using custom validation attribute?
By default, the System.ComponentModel.Annotations library provides different validation attributes. However, to add a new or custom validation, users can create a custom validation attribute and apply it to their model class. To create an attribute: Create a Blazor Server Application with latest .NET support. Install the System.ComponentModel.Annotations NuGet package to perform custom validation in Created project. Create a new folder named Models in the main application and add the following *.cs files –EmployeeDetails, OrganizationValidationAttribute to it as shown below. Add a model EmployeeDetails class name in the EmployeeDetails.csfile. using System.ComponentModel.DataAnnotations; namespace BlazorServerApp.Models { public class EmployeeDetails { [Required] public string? Name { get; set; } [Required] public string? Organization { get; set; } } } Create a new OrganizationValidationAttribute.cs file and then the OrganizationValidationAttribute class, which is derived from ValidationAttribute. The ValidationAttribute from System.ComponentModel.Annotations acts as the base class for validation.[OrganizationValidationAttribute.cs] using System.ComponentModel.DataAnnotations; namespace BlazorServerApp.Models { public class OrganizationValidationAttribute : ValidationAttribute { public string? ValidOrganizationName { get; set; } protected override ValidationResult? IsValid ( object? value, ValidationContext? validationContext ) { string fieldValue = value!.ToString()!.ToLower(); if (fieldValue.Equals(ValidOrganizationName?.ToLower())) return null; return new ValidationResult(ErrorMessage, new[] { validationContext?.MemberName }.Cast<string>()); } } } The ValidOrganizationName property can be set from the model EmployeeDetails class. Following that, override the IsValid method, which takes two parameters, value and validationContext. The value parameter contains the value that the user entered in the Organization field. The validationContext parameter is used to explain the context in which validation is performed. If the value is equal to the ValidOrganizationName, no errors will be thrown; otherwise, an error message returns. Add the following custom validation attribute to the Organization property. using System.ComponentModel.DataAnnotations; namespace BlazorServerApp.Models { public class EmployeeDetails { [Required] public string? Name { get; set; } //Here OrganizationValidation is a Customvalidation Attribute [Required] [OrganizationValidation(ErrorMessage = "Invalid customer log-in.", ValidOrganizationName = "Syncfusion")] public string? Organization { get; set; } } } Moving back to the Blazor Server application, add the following code to the Index.razor page to render a form with validation settings.[Index.razor] @page "/" @using BlazorServerApp.Models <EditForm Model="_product" OnValidSubmit="Submit" style="width:600px;"> <DataAnnotationsValidator /> <ValidationSummary/> <div class="form-group row"> <label for="name" class="col-md-2 col-form-label">Name:</label> <label for="name" class="col-md-2 col-form-label">Name:</label> <div class="col-md-10"> <InputText id="name" class="form-control" @bind-Value="_product.Name" /> <ValidationMessage For="@(() => _product.Name)" /> </div> </div> <div class="form-group row"> <label for="organization" class="col-md-2 col-form-label">Organization:</label> <div class="col-md-10"> <InputText id="supplier" class="form-control" @bind-Value="_product.Organization" /> <ValidationMessage For="@(() => _product.Organization)" /> </div> </div> <div class="row"> <div class="col-md-12 text-right"> <button type="submit" class="btn btn-success">Submit</button> </div> </div> </EditForm> @code{ private EmployeeDetails _product = new EmployeeDetails(); public void Submit () => Console.WriteLine($"{_product.Name}, {_product.Organization}"); } The following outputs will be seen after submitting the form. View Sample in GitHub
How do I validate a nested complex model in Blazor?
The built-in DataAnnotationsValidator allows you to validate form input using data annotations, but it only validates top-level properties bound to the form and not child or complex type properties. To validate the nested complex model, replace the DataAnnotationsValidator with the ObjectGraphDataAnnotationsValidator, which validates the entire object, including child and complex type properties in the form. Install the following package via Package Manager Console in order to use the ObjectGraphDataAnnotationsValidator. PM> Install-Package Microsoft.AspNetCore.Components.DataAnnotations.Validation -Version 3.2.0-rc1.20223.4 Create a new Folder named StudentDetails in the main application and add the class named Student.cs to the StudentDetails folder. In Student.cs file, create two model classes -Student and PersonalDetails. Here, add ValidateComplexType belonging to the ObjectGraphDataAnnotationsValidator above the complex type declaration. using System.ComponentModel.DataAnnotations; namespace Validating_Complex_Model_in_Blazor.StudentDetails { public class Student { public Student () { Details = new PersonalDetails(); } [Required] public string Name { get; set; } [Required] public string Department { get; set; } [ValidateComplexType] public PersonalDetails Details { get; set; } } public class PersonalDetails { [Required] public int Age { get; set; } [Required] public string? Address { get; set; } } } Create an Index.razor page with the EditForm and Input components shown in the code sample below. Set the Model property of the EditForm component to the Student class instance. Additionally, the ObjectGraphDataAnnotationsValidator and ValidationSummary tags are used for validation and the display of validation summary, respectively. @page "/" @using Validating_Complex_Model_in_Blazor.StudentDetails <EditForm Model="@_student" OnValidSubmit="@HandleValidSubmit" OnInvalidSubmit="@HandleInvalidSubmit"> <ObjectGraphDataAnnotationsValidator /> <ValidationSummary /> <div class="form-group"> <label for="name">Name: </label> <InputText Id="name" Class="form-control" @bind-Value="@_student.Name"></InputText> <ValidationMessage For="@(() => _student.Name)" /> </div> <div class="form-group"> <label for="department">Department: </label> <InputText Id="department" Class="form-control" @bind-Value="@_student.Department"></InputText> <ValidationMessage For="@(() => _student.Department)" /> </div> <div class="form-group"> <label for="address">Address: </label> <InputTextArea Id="address" Class="form-control" @bind-Value="@_student.Details.Address"></InputTextArea> <ValidationMessage For="@(() => _student.Details.Address)" /> </div> <button type="submit">Submit</button> </EditForm> @code { public string StatusMessage; public Student _student = new Student(); public void HandleValidSubmit() { StatusMessage = "It's a valid submission."; } public void HandleInvalidSubmit() { StatusMessage = "It's an invalid submission. Please see the error message(s) listed below."; } } View Sample in GitHub
What is an EditContext and how do I define and use it in a form?
The EditContext of the form stores information about the editing process, such as which fields have been changed and which validation messages are currently displayed. To manually pass the EditContext to the EditForm, follow the steps below. Create a new Customer.cs file and model Customer class. public class Customer { [Required] public string Name { get; set; } [Required] [StringLength(4, ErrorMessage = "The organization code must be less than 5 characters in length.")] public string OrganizationCode { get; set; } } Insert an EditForm component into the Index.razor page. Then, make instances of the Customer class and the EditContext, and assign the Customer class instance to the EditContext instance. Finally, bind the EditContext instance to the EditContext property in the EditForm component. @page "/" <EditForm EditContext="@editContext"> <DataAnnotationsValidator /> <ValidationSummary /> </EditForm> @code { private Customer _customer = new Customer(); private EditContext editContext; protected override void OnInitialized() { editContext = new(_customer); } } As the EditContext stores all the form information, it can be used to validate the form components. Add the Razor code as given below with input texts and a button. When a form is submitted, the Validate() method is invoked to perform validation. @page "/" <EditForm EditContext="@editContext"> <DataAnnotationsValidator /> <ValidationSummary /> <div class="form-group"> <label for="name">Name:</> <InputText id="name" @bind-Value="_customer.Name" /> <ValidationMessage For="="@(() => _customer.Name)" /> </div> <div class="form-group"> <label for="organizationCode">Organization Code:</> <InputText id="organizationCode" class="form-control" @bind-Value="_customer.OrganizationCode"/> <ValidationMessage For="="@(() => _customer.OrganizationCode)" /> </div> <div style="margin-top: 10px;"> <button type="submit" class="btn btn-primary" @onclick="Submit">Submit</button> </div> </EditForm> View Sample in GitHub
How can I add custom CSS class names to input components based on the validation state despite bootstrap and other CSS frameworks?
To add custom CSS class names to input components despite bootstrap and other CSS framework styling, follow the steps below. In the wwroot/css/site.css stylesheet, include the following styles. .validField { outline: 2px dotted green; } .invalidField { outline: 2px dotted red; } Create a new Customer.cs and model Customer class. using System.ComponentModel.DataAnnotations; namespace CustomCSS_Validation_InputComponent { public class Customer { [Required] public string Name { get; set; } [Required] [StringLength(4, ErrorMessage = "The organization code must be less than 5 characters in length.")] public string OrganizationCode { get; set; } } } Create a new CustomFieldCssClassProvider.cs and then the CustomFieldCssClassProvider class.Inherit the CustomFieldCssClassProvider class from FieldCssClassProvider and override the GetFieldCssClass method, which helps to check for validation messages with the EditContext and returns the “validField” or “invalidField” class name to the appropriate field. using Microsoft.AspNetCore.Components.Forms; using System.Linq; namespace FormBootstrapCSS.Data { public class CustomFieldCssClassProvider : FieldCssClassProvider { public override string GetFieldCssClass(EditContext editContext, in FieldIdentifier fieldIdentifier) { var isValid = !editContext.GetValidationMessages(fieldIdentifier).Any(); return isValid ? "validField" : "invalidField"; } } } Add the form design code as well as the code for input components validation to the Index.razor page. Here, the SetFieldCssClassProvider method in the EditContext class is used to set the custom CSS name to the appropriate field based on the validation result returned by the CustomFieldCssClassProvider class, whose instance is passed into the method. @page "/" <EditForm EditContext="@editContext" OnValidSubmit="@Submit"> <DataAnnotationsValidator /> <ValidationSummary /> <div class="mt-2 col-md-12"> Name: <InputText id="name" @bind-Value="_customer.Name" /> </div> <div class="mt-2 col-md-12"> Organization Code: <InputText id="organizationCode" @bind-Value="_customer.OrganizationCode" /> </div> <div class="mt-2 col-md-12"> <button type="submit">Submit</button> </div> </EditForm> @code { private Customer _customer = new Customer(); private EditContext editContext; protected override void OnInitialized() { editContext = new(_customer); editContext.SetFieldCssClassProvider(new CustomFieldCssClassProvider()); } private void Submit() { …….. . . } } View Sample in GitHub