Q:

How do you display form validation error messages adjacent to the form fields in Blazor? How do you display a validation message specific to a field in a Blazor form?

0

This code will help you to understand how to display form validation error messages adjacent to the form fields in Blazor and to display a validation message specific to a field in a Blazor form.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

How do you display form validation error messages adjacent to the form fields in Blazor? How do you display a validation message specific to a field in a Blazor form?
You have to use the <ValidationMessage> tag with the “For” attribute lambda expression pointing to the form field.

[Person.cs]

using System.ComponentModel.DataAnnotations;
public class Person
    {
        [Required]
        [StringLength(15, ErrorMessage = "{0} length must be between {2} and {1}.", MinimumLength = 6)]
        public string FirstName { get; set; }

        [Required]
        [DataType(DataType.Password)]
        [StringLength(15, ErrorMessage = "{0} length must be between {2} and {1}.", MinimumLength = 6)]
        public string LastName { get; set; }

        [Required]
        [Range(1, 100, ErrorMessage = "Age should a number between (1-100).")]
        public int Age { get; set; }
    }

[FormValidation.Razor]

<EditForm Model="@person" OnValidSubmit="@HandleValidSubmit">
  <DataAnnotationsValidator />

  <label for="firstname">First Name: </label>
  <InputText Id="firstname" @bind-Value="@person.FirstName"></InputText>
  <ValidationMessage For="@(() => person.FirstName)" />

  <label for="lastname">Last Name: </label>
  <InputText Id="lastname" @bind-Value="@person.LastName"></InputText>
  <ValidationMessage For="@(() => person.LastName)" />

  <label for="age">Age: </label>
  <InputNumber Id="age" @bind-Value="@person.Age"></InputNumber>
  <ValidationMessage For="@(() => person.Age)" />

  <button type="submit">Submit</button>
</EditForm>
@code {
    private Person person = new Person();
    private void HandleValidSubmit()
    {
        Console.WriteLine("OnValidSubmit");
    }
}

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Similar questions


need a help?


find thousands of online teachers now