Blazor Validation Made Easy with Radzen

Introduction

Blazor is an open-source web framework that allows developers to build web applications using C# and .NET, running on the client side through WebAssembly or the server side through SignalR. With Blazor, developers can build modern web applications using familiar tools and languages, while also benefiting from the performance and security features provided by the .NET ecosystem. One important aspect of building any application, including those with Blazor, is ensuring that data input is validated before use. In this article, we will explore the different types of validation available in Blazor and how to implement them in your applications.

What is validation in Blazor?

Validation is the process of checking or verifying whether something is accurate, reliable, or consistent. This process can be applied to various fields such as software engineering, data analysis, and scientific research. In software engineering, validation refers to testing software to determine if it meets the user's requirements and expected functionality. In data analysis, validation ensures that the input data is accurate and complete before any meaningful analysis can be performed. In scientific research, validation involves verifying the methods and results of a study to ensure that they are valid and unbiased. Overall, validation plays a crucial role in ensuring the quality and reliability of various products and services by assuring that they meet specific standards and requirements.

Server-side validation in Blazor

Blazor supports server-side validation using the same data annotations and validation attributes that are used for client-side validation. Server-side validation is performed when the form is submitted to the server before the data is saved to the database.

To perform server-side validation in Blazor, you need to add the ValidationMessage component to your form, which will display any validation error messages that are returned from the server

Client-side validation in Blazor

Blazor also supports client-side validation, which is performed in the browser using JavaScript. Client-side validation can provide a faster and more responsive user experience because it does not require a round-trip to the server.

To perform client-side validation in Blazor, you need to add the ValidationMessage component to your form, which will display any validation error messages that are returned from the client-side validation

Types of Validation in Blazor

There are several types of validation available in Blazor, including:

Required validation- This type of validation ensures that a required field is not left empty. For example, if a user is required to enter their name, this validation will ensure that the user cannot submit the form without filling in this field.

Regular expression validation- This type of validation ensures that the input follows a specific pattern. For example, if a user is required to enter a phone number, this validation will ensure that the input follows the format of a phone number (i.e. XXX-XXX-XXXX).

Range validation- This type of validation ensures that the input falls within a specific range of values. For example, if a user is required to enter their age, this validation will ensure that the input falls within a specific range (i.e. between 18 and 65 years old).

Compare validation- This type of validation compares the input of two fields to ensure that they match. For example, if a user is required to enter their password twice to confirm it, this validation will ensure that both passwords match.

Custom validation- This type of validation allows developers to create their validation logic to ensure that the input meets specific requirements.

How to Implementing Validation in Blazor?

Blazor provides a built-in validation system that allows developers to easily implement validation in their applications. This system is based on data annotations, which are attributes that can be applied to model properties to specify validation rules. Here is an example of a model with data annotations:

public class UserModel
{
    [Required(ErrorMessage = "Please enter your name.")]
    public string Name { get; set; }

    [EmailAddress(ErrorMessage = "Please enter a valid email address.")]
    public string Email { get; set; }

    [Range(18, 65, ErrorMessage = "You must be between 18 and 65 years old.")]
    public int Age { get; set; }

    [Compare("Password", ErrorMessage = "The passwords do not match.")]
    public string ConfirmPassword { get; set; }

    public string Password { get; set; }
}

In this example, the UserModel class has several properties with data annotations. The Name property is required, meaning that the user must enter a value for this property. The Email property has an email address validation rule, meaning that the input must be in the format of an email address. The Age property has a range validation rule, meaning the input must be between 18 and 65. The ConfirmPassword property has a compare validation rule, meaning it must match the Password property.

<EditForm Model="@userModel" OnValidSubmit="@CreateAccount">
    <DataAnnotationsValidator />

    <div class="form-group">
        <label for="name">Name:</label>
        <InputText id="name" class="form-control" @bind-Value="@userModel.Name" />
        <ValidationMessage For="@(() => userModel.Name)" />
    </div>

    <div class="form-group">
        <label for="email">Email:</label>
        <InputText id="email" class="form-control" @bind-Value="@userModel.Email" />
        <ValidationMessage For="@(() => userModel.Email)" />
    </div>

    <div class="form-group">
        <label for="age">Age:</label>
        <InputText id="age" class="form-control" @bind-Value="@userModel.Age" />
        <ValidationMessage For="@(() => userModel.Age)" />
    </div>

    <div class="form-group">
        <label for="password">Password:</label>
        <InputText id="password" class="form-control" @bind-Value="@userModel.Password" />
        <ValidationMessage For="@(() => userModel.Password)" />
    </div>

    <div class="form-group">
        <label for="cpassword">Confirm Password:</label>
        <InputText id="cpassword" class="form-control" @bind-Value="@userModel.ConfirmPassword" />
        <ValidationMessage For="@(() => userModel.ConfirmPassword)" />
    </div>

    
    <button type="submit" class="btn btn-primary">Create Account</button>
</EditForm>

In this example, we are using the DataAnnotationsValidator component for validation using data annotations. The ValidationMessage component is used to display any validation error messages for the Name and Email properties.

How to implement Radzen Validator in Blazor App?

Radzen is a popular low-code development platform that simplifies the creation of web applications. With Radzen, developers can quickly build and deploy applications using drag-and-drop tools and pre-built components. One important aspect of any web application is data validation, which ensures that user input is valid and meets certain requirements. In this article, we will explore how to implement Radzen validation in a Blazor application with code examples.

What is Radzen Validation?

Radzen validation is a powerful feature that allows developers to add validation rules to form inputs in a Blazor application. This feature ensures that user input is valid and meets certain criteria, such as a required field, a minimum or maximum value, or a regular expression pattern. Radzen validation provides a user-friendly experience by displaying error messages when the input is invalid.

Radzen validation can be applied to various form controls, such as textboxes, checkboxes, and dropdowns. The validation rules can be defined using attributes, such as [Required], [Range], and [RegularExpression], or by implementing a custom validation method. When a user submits a form, Radzen validation automatically checks the input against the defined rules and displays error messages for any invalid input.

Types of Radzen Validators

Radzen provides a variety of validators that can be used to validate user input in forms. Here are some of the most commonly used Radzen validators:

RadzenRequiredValidator- This validator ensures that a form field is not left empty. It displays an error message if the user tries to submit the form without entering a value for the required field.

<RadzenTextBox @bind-Value="Name"  Name="name"/>
  <RadzenRequiredValidator Text="Name is required" Component="name" />

RadzenRegularExpressionValidator- This validator checks whether the input matches a specified regular expression pattern. It can be used to ensure that the user enters data in a specific format, such as a valid email address or a phone number.

<RadzenTextBox @bind-Value="Name"  Name="Email"/>
  <RadzenRegularExpressionValidator Text="Invalid email format" Component="Email" Pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}$" />

RadzenRangeValidator- This validator ensures that the input falls within a specified range of values. It can be used to validate numeric input, such as a user's age or salary.

<RadzenTextBox @bind-Value="Number"  Name="number"/>
  <RadzenRangeValidator @ref="myRangeValidator" Component="number" Max="10" />

RadzenCompareValidator- This validator compares the values of two form fields and displays an error message if they do not match. It can be used to validate passwords and confirm password fields, for example.

<RadzenTextBox @bind-Value="CPassword"  Name="cpassword"/>
 <RadzenCompareValidator @ref="myCompareValidator" Component="cpassword" ControlToCompare="Password" Operator="Equal" ErrorMessage="Passwords do not match." />

RadzenStringLengthValidator- This validator checks whether the length of the input falls within a specified range of values. It can be used to validate text input, such as a user's name or address.

<RadzenTextBox @bind-Value="Name"  Name="name"/>
  <RadzenStringLengthValidator @ref="myStringLengthValidator" Component="name" MinLength="5" MaxLength="10" ErrorMessage="Input must be between 5 and 10 characters long." />

RadzenCustomValidator- This validator allows you to write custom validation logic using C# code. It can be used to implement complex validation rules that cannot be expressed using built-in validators.

<RadzenTextBox Type="text" @bind-Value="Name"  Name="name"/>
  <RadzenCustomValidator @ref="myCustomValidator" Component="name" ValidationCallback="ValidateInput" ErrorMessage="Input is not valid." />

RadzenEmailValidator- This validator checks whether the input is a valid email address. It can be used to ensure that the user enters a properly formatted email address.

<RadzenTextBox Type="email" Name="email" @bind-Value="employee.Email"/>
  <RadzenEmailValidator Component="email" Text="Please enter a valid email address" />

RadzenNumericValidator- This validator ensures that the input is a valid numeric value. It can be used to validate numeric input, such as a user's age or salary.

<RadzenTextBox Type="date" @bind-Value="employee.Age" Name="age"/>
  <RadzenNumericValidator Component="age" Text="Please enter a valid age" />

RadzenFileValidator- This validator checks whether the user has selected a file in a file input field. It can be used to ensure that the user selects a file before submitting the form.

<RadzenUpload @bind-Value="file" Name="file"/>
  <RadzenFileValidator Component="file" Text="Please select a file" />

RadzenUrlValidator- This validator checks whether the input is a valid URL. It can be used to ensure that the user enters a properly formatted URL.

<RadzenTextBox @bind-Value="website" Name="url"/>
  <RadzenUrlValidator Component="url" Text="Please enter a valid URL" />

RadzenDropDownValidator- This validator checks whether a value is selected in a dropdown list. It can be used to ensure that the user selects a value from a dropdown list before submitting the form.

<RadzenDropDown @bind-Value="selectedOption" Data="@options" Name="dropdownvalue">
  <RadzenDropDownValidator Component="dropdownvalue" Text="Please select an option" />

RadzenCheckBoxValidator- This validator checks whether a checkbox is checked or not. It can be used to ensure that the user checks a checkbox before submitting the form.

<RadzenCheckBox @bind-Value="agreeToTerms" Name="checkboxvalue" />
  <RadzenCheckBoxValidator Component="checkboxvalue" Text="Please agree to the terms" />

How to Implement Radzen Validation in a Blazor Application?

Create a Component and write a code.

@using Radzen
@using System.Text.Json

<div class="container my-4">
    <div class="row">
        <div class="col">
            <RadzenCard class="w-100 mb-4" >
            <RadzenCheckBox @bind-Value=@popup Name="popup"></RadzenCheckBox>
                <RadzenLabel Text="Display validators as popup" For="popup" Style="margin-left: 8px; vertical-align: middle;" />
            </RadzenCard>
        </div>
    </div>
    <div class="row">
        <div class="col-lg-6 offset-lg-3">
            <RadzenTemplateForm TItem="Model" Data=@model Submit=@OnSubmit InvalidSubmit=@OnInvalidSubmit>
                <RadzenFieldset Text="Personal information">
                    <div class="row mb-5">
                        <div class="col-md-4">
                            <RadzenLabel Text="First Name" />
                        </div>
                        <div class="col">
                            <RadzenTextBox style="display: block" Name="FirstName" @[email protected] class="w-100" />
                            <RadzenRequiredValidator Component="FirstName" Text="First name is required" Popup=@popup Style="position: absolute"/>
                        </div>
                    </div>
                    <div class="row mb-5">
                        <div class="col-md-4">
                            <RadzenLabel Text="Last Name" />
                        </div>
                        <div class="col">
                            <RadzenTextBox style="display: block" Name="LastName" @[email protected]  class="w-100" />
                            <RadzenRequiredValidator Component="LastName" Text="Last name is required" Popup=@popup Style="position: absolute"/>
                        </div>
                    </div>
                    <RadzenButton ButtonType="ButtonType.Submit" Text="Submit" ></RadzenButton>
                </RadzenFieldset>
            </RadzenTemplateForm>
        </div>
    </div>
</div>

<EventConsole @ref=@console />

@code {
    class Model
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }

    bool popup;

    Model model = new Model();
    EventConsole console;

    void OnSubmit(Model model)
    {
        console.Log($"Submit: {JsonSerializer.Serialize(model, new JsonSerializerOptions() {  WriteIndented = true })}");
    }

    void OnInvalidSubmit(FormInvalidSubmitEventArgs args)
    {
        console.Log($"InvalidSubmit: {JsonSerializer.Serialize(args, new JsonSerializerOptions() {  WriteIndented = true })}");
    }
}

Output

Blazor Validation Made Easy with Radzen

Conclusion

Validation is an important aspect of web development that ensures that user input is accurate and secure. Blazor provides built-in support for validation using data annotations, as well as the ability to create custom validation rules using the ValidationAttribute class. By incorporating validation into your Blazor applications, you can ensure that your users have a positive experience and that your application is secure and reliable.

Blazor provides support for both server-side and client-side validation using data annotations and validation attributes. Server-side validation is performed when the form is submitted to the server, while client-side validation is performed in the browser using JavaScript. By incorporating both server-side and client-side validation into your Blazor applications, you can ensure that your users have a positive experience and that your application is secure and reliable.

FAQ

Q 1- How do I validate my Blazor model?

Annotate the properties of your model class with DataAnnotations attributes to specify validation rules. For example, you can use the Required attribute to mark a property as required:

Q 2- How do you manually trigger the form validation in Blazor?

In Blazor, you can manually trigger the validation of a form by calling the Validate method of the EditContext class. The EditContext class is a container for a form's validation state and is automatically created when you use the EditForm component.

Q 3- What are DataAnnotations attributes in Blazor?

DataAnnotations attributes are a set of predefined attributes that can be used to annotate model properties to specify validation rules such as required fields, string length, and regular expressions. To use DataAnnotations attributes for validation in Blazor, you need to annotate the properties of your model class with the appropriate attribute, such as the Required attribute for a required field.

Q 4- How do I use the EditForm component for validation in Blazor?

The EditForm component is a built-in component in Blazor that helps you implement validation for forms. It automatically tracks changes to form fields and provides built-in validation messages. To use the EditForm component for validation in Blazor, you need to wrap your form inside an EditForm component and annotate the properties of your model class with the appropriate DataAnnotations attributes.

Q 5- Can I implement custom validation logic in Blazor?

Yes, you can implement custom validation logic in Blazor by creating your own validation functions and using them in your code. You can also create custom validation attributes that can be used in your model classes.

Q 6- How do I display validation messages in Blazor?

You can display validation messages in Blazor by using the ValidationMessage component, which automatically displays the appropriate validation message for a form field. You can also customize the appearance and behavior of validation messages using CSS and JavaScript.


Similar Articles