Is it possible to add validation without dataannotations on class?

Usually I would have ValidationMessage element that used the DataAnnotation from AppUser.Email, but is it possible to add validation (let's say "the field is required" without the use of data

      <div class="col-md-6">

        <SfTextBox ID="email" @bind-Value="AppUser.Email" ShowClearButton="true" Placeholder="Skriv inn epost"></SfTextBox>

      </div>


1 Reply 1 reply marked as answer

KP Kokila Poovendran Syncfusion Team January 3, 2024 11:48 AM UTC

Hi Art Vandelay,


Thank you for reaching out with your question about adding validation without using DataAnnotations on a class.


While DataAnnotations provide a standardized and elegant way to define validation rules, if you prefer to implement validation directly in the Blazor component without relying on DataAnnotations, you can do so using conditional checks within the component. Below is a sample code snippet demonstrating how you can add a simple "field is required" validation for the SfTextBox:


<div class="col-md-6">

    <SfTextBox ID="email" @bind-Value="appUser.Email" ShowClearButton="true" Placeholder="Enter email" Width="350px"></SfTextBox>

    @if (string.IsNullOrWhiteSpace(appUser.Email))

    {

        <p style="color: red;">Email is required.</p>

    }

</div>

 

@code {

    private AppUser appUser = new AppUser();

 

    public class AppUser

    {

        public string Email { get; set; }

        public string FirstName { get; set; }

        public string LastName { get; set; }

    }

}


In this example, we manually check if the email field is null or consists only of whitespaces. If it is, we display a validation message. This approach allows you to have custom validation logic within your component.


If you have any further questions or if there's anything else I can assist you with, please feel free to let me know.


Marked as answer
Loader.
Up arrow icon