Blazorise Validation component

The Validation component allows you to verify your data, helping you find and correct errors.

Validation components are used to provide simple form validation for Blazorise input components.

The basic structure for validation component is:

  • <Validations> optional container for manual validation
    • <Validation> input container
      • <Feedback> messages placeholder
        • <ValidationSuccess> success message
        • <ValidationError> error message
        • <ValidationNone> message when nothing has happened
    • <ValidationSummary> lists all error messages

For the most part you will need to use just the <Validation> component along with <ValidationSuccess> and <ValidationError>. By default every validation will run automatically when input value changes. You must set the Validator event handler where you can define the validation rules and return the validation result.

Examples

Validating using Methods handlers

Method handlers are the easiest and quickest way to validate fields. Therefore, we give you a set of predefined validation handlers that can be accessed through the ValidationRule helpers class and assigned to the Validator parameter.

Apart from using the pre-built handler methods, you can also create your own. For example, you can see the custom ValidateEmail handler in the following code-snippet.

Enter valid name!
Please enter the email.
<Validation Validator="ValidationRule.IsNotEmpty">
    <TextEdit Placeholder="Enter name">
        <Feedback>
            <ValidationNone>Please enter the name.</ValidationNone>
            <ValidationSuccess>Name is good.</ValidationSuccess>
            <ValidationError>Enter valid name!</ValidationError>
        </Feedback>
    </TextEdit>
</Validation>

<Validation Validator="ValidateEmail">
    <TextEdit Placeholder="Enter email">
        <Feedback>
            <ValidationNone>Please enter the email.</ValidationNone>
            <ValidationSuccess>Email is good.</ValidationSuccess>
            <ValidationError>Enter valid email!</ValidationError>
        </Feedback>
    </TextEdit>
</Validation>
@code{
    void ValidateEmail( ValidatorEventArgs e )
    {
        var email = Convert.ToString( e.Value );

        e.Status = string.IsNullOrEmpty( email ) ? ValidationStatus.None :
            email.Contains( "@" ) ? ValidationStatus.Success : ValidationStatus.Error;
    }
}
The same structure is for all Edit components(check, radio, select, etc). Note that for some components there are some special rules when defining the validation structure. For example for Check you must use ChildContent tag along with the Feedback tag. This is a limitation in Blazor, hopefully it will be fixed in the future.
<Validation Validator="@ValidateCheck">
    <Check TValue="bool">
        <ChildContent>
            Check me out
        </ChildContent>
        <Feedback>
            <ValidationError>You must check me out!</ValidationError>
        </Feedback>
    </Check>
</Validation>
@code{
    void ValidateCheck( ValidatorEventArgs e )
    {
        // ...
    }
}

Validating using Data Annotations

To use data annotations with Blazorise you must combine both Validation and the Validations components. The Validations component will act as a group for a fields used inside of Validation component. To make it all work you must meet two requirements:
  1. Validations component must contain reference to the validated POCO through the Model parameter.
  2. Input component must bind to the model field through the @bind-{Value}(i.e. @bind-Text)
After those two requirements are met the Blazorise will have enough information to know how to use data annotations.
The Name field is required.
The Email field is required.
Password is required
Confirm Password is required
@using System.ComponentModel.DataAnnotations

<Validations Mode="ValidationMode.Auto" Model="@user">
    <Validation>
        <Field Horizontal>
            <FieldLabel ColumnSize="ColumnSize.Is2">Full Name</FieldLabel>
            <FieldBody ColumnSize="ColumnSize.Is10">
                <TextEdit Placeholder="First and last name" @bind-Text="@user.Name">
                    <Feedback>
                        <ValidationError />
                    </Feedback>
                </TextEdit>
            </FieldBody>
        </Field>
    </Validation>
    <Validation>
        <Field Horizontal>
            <FieldLabel ColumnSize="ColumnSize.Is2">Email</FieldLabel>
            <FieldBody ColumnSize="ColumnSize.Is10">
                <TextEdit Placeholder="Enter email" @bind-Text="@user.Email">
                    <Feedback>
                        <ValidationError />
                    </Feedback>
                </TextEdit>
            </FieldBody>
        </Field>
    </Validation>
    <Validation>
        <Field Horizontal>
            <FieldLabel ColumnSize="ColumnSize.Is2">Password</FieldLabel>
            <FieldBody ColumnSize="ColumnSize.Is10">
                <TextEdit Role="TextRole.Password" Placeholder="Password" @bind-Text="@user.Password">
                    <Feedback>
                        <ValidationError />
                    </Feedback>
                </TextEdit>
            </FieldBody>
        </Field>
    </Validation>
    <Validation>
        <Field Horizontal>
            <FieldLabel ColumnSize="ColumnSize.Is2">Re Password</FieldLabel>
            <FieldBody ColumnSize="ColumnSize.Is10">
                <TextEdit Role="TextRole.Password" Placeholder="Retype password" @bind-Text="@user.ConfirmPassword">
                    <Feedback>
                        <ValidationError />
                    </Feedback>
                </TextEdit>
            </FieldBody>
        </Field>
    </Validation>
</Validations>
@code{
    User user = new User();

    public class User
    {
        [Required]
        [StringLength( 10, ErrorMessage = "Name is too long." )]
        public string Name { get; set; }

        [Required]
        [EmailAddress( ErrorMessage = "Invalid email." )]
        public string Email { get; set; }

        [Required( ErrorMessage = "Password is required" )]
        [StringLength( 8, ErrorMessage = "Must be between 5 and 8 characters", MinimumLength = 5 )]
        [DataType( DataType.Password )]
        public string Password { get; set; }

        [Required( ErrorMessage = "Confirm Password is required" )]
        [StringLength( 8, ErrorMessage = "Must be between 5 and 8 characters", MinimumLength = 5 )]
        [DataType( DataType.Password )]
        [Compare( "Password" )]
        public string ConfirmPassword { get; set; }

        [Required]
        public string Title { get; set; }

        [Range( typeof( bool ), "true", "true", ErrorMessage = "You gotta tick the box!" )]
        public bool TermsAndConditions { get; set; }
    }
}

Validating using Pattern

If you want to validate input by using regular expression instead of Validator handlers you can use Pattern patameter. Components that supports pattern attribute are TextEdit, NumericEdit and DateEdit.
Pattern does not match!
<Validation UsePattern>
    <TextEdit Pattern="[A-Za-z]{3}">
        <Feedback>
            <ValidationError>Pattern does not match!</ValidationError>
        </Feedback>
    </TextEdit>
</Validation>

Async validation

In case you need to run validation using the external source or rest API, we also support async validation. The process is similar to regular validator. You just need to define awaitable handler using the AsyncValidator parameter.
Enter valid name!
@using System.Threading

<Validation AsyncValidator="@ValidateNameAsync">
    <TextEdit Placeholder="Enter name">
        <Feedback>
            <ValidationError>Enter valid name!</ValidationError>
        </Feedback>
    </TextEdit>
</Validation>
@code{
    Random random = new Random();

    async Task ValidateNameAsync( ValidatorEventArgs e, CancellationToken cancellationToken )
    {
        cancellationToken.ThrowIfCancellationRequested();

        // some long running task or call to the rest API
        await Task.Delay( random.Next( 1500 ) );

        e.Status = string.IsNullOrEmpty( Convert.ToString( e.Value ) )
            ? ValidationStatus.Error
            : ValidationStatus.Success;
    }
}

Manual validation

Sometimes you don’t want to do validation on every input change. In that case you use <Validations> component to group multiple validations and then run the validation manually.

In this example you can see how the <Validations>component is used to enclose multiple validation components and the Mode attribute is set to Manual. Validation is executed only when clicked on submit button.
<Validations @ref="validations" Mode="ValidationMode.Manual">
    <Validation Validator="@ValidationRule.IsNotEmpty">
        <Field>
            <TextEdit Placeholder="Enter first name" />
        </Field>
    </Validation>
    <Validation Validator="@ValidationRule.IsNotEmpty">
        <Field>
            <TextEdit Placeholder="Enter last name" />
        </Field>
    </Validation>
    <Button Color="Color.Primary" Clicked="@Submit">Submit</Button>
</Validations>
@code{
    Validations validations;

    async Task Submit()
    {
        if ( await validations.ValidateAll() )
        {
            // do something
        }
    }
}

Localization

If you want to localize your validation messages, we got you covered. Blazorise will provide you with an API and all the required information needed for you to make localization. This is done through the MessageLocalizer API. But before you use it we need to break it down a little so you can understand it better how it works.

A MessageLocalizer is fairly straight forward. It accepts two parameters and returns a string. It’s signature is as following string Localize(string message, IEnumerable<string> arguments).

Where:

  • format raw validation message
  • arguments list of arguments or values for populating the message

So now that you know what the API consist of, we need to talk what is the content of the API. And the most important is the message parameter. Each message value will be represented as a raw message in the form before the actual message was formatted.

For example if you have a [Required] attribute set on your model field, this message will be "The {0} field is required.". And the arguments will contain all the values needed to populate the placeholders inside of the message.

Example

For the basic example we’re going to use MessageLocalizer directly on a Validation component.
@using Blazorise.Localization

<Validation MessageLocalizer="@Localize">
</Validation>
@code{
    [Inject] ITextLocalizer<LocalizationValidationExample> L { get; set; }

    string Localize( string message, IEnumerable<string> arguments )
    {
        // You should probably do null checks here!
        return string.Format( L[message], arguments.ToArray() );
    }
}

Global Options

Setting the MessageLocalizer on each Validation is a good for approach if you want to control every part of your application. But a more practical way is to define it globally. If you remember from the Start Guide, we already have Validation defined in our application startup so we just need to modify it a little.

Validation summary

Sometimes you don’t want to show error messages under each field. In those situations you can use ValidationSummary component. Once placed inside of Validations it will show all error messages as a bullet list.
<Validations Mode="ValidationMode.Manual">
    <ValidationSummary Label="Following error occurs..." />

    @*other validation fields*@
</Validations>

Auto Validation

By default form is auto-validated on page load. In case you want to disable it and validate only when user starts entering fields, now you can. Just set ValidateOnLoad to false.
...
<Validations Mode="ValidationMode.Auto" ValidateOnLoad>
    ...
</Validations>

Validation rules

In Blazorise you can use some of the predefined validation rules. eg
...
<Validation Validator="@ValidationRule.IsNotEmpty">
    ...
</Validation>

List of the currently available validators.

Validator Description
IsEmpty Check if the string is null or empty.
IsNotEmpty Check if the string is not null or empty.
IsEmail Check if the string is an email.
IsAlpha Check if the string contains only letters (a-zA-Z).
IsAlphanumeric Check if the string contains only letters and numbers.
IsAlphanumericWithUnderscore Check if the string contains only letters, numbers and underscore.
IsUppercase Check if the string is uppercase.
IsLowercase Check if the string is lowercase.

API

Attributes

Validations

Name Description Type Default
Mode Defines the validation mode for validations inside of this container. ValidationMode Auto
EditContext Supplies the edit context explicitly. If using this parameter, do not also supply Model, since the model value will be taken from the Model property. EditContext null
Model Specifies the top-level model object for the form. An edit context will be constructed for this model. object null
MissingFieldsErrorMessage Message that will be displayed if any of the validations does not have defined error message. string null
ValidatedAll Event is fired only after all of the validation are successful. EventCallback
StatusChanged Event is fired whenever there is a change in validation status. EventCallback
ValidateOnLoad Run validation only when user starts entering values. bool false
HandlerType Defines the default handler type that will be used by the validation, unless it is overriden by Validation.HandlerType property. Type null

Validation

Name Description Type Default
Status Gets or sets the current validation status. ValidationStatus None
StatusChanged Event is fired whenever there is a change in validation status.
Validator Validates the input value after it has being changed. Action<ValidatorEventArgs>
AsyncValidator Asynchronously validates the input value after it has being changed. Func<ValidatorEventArgs, CancellationToken, Task>
UsePattern Forces validation to use regex pattern matching instead of default validator handler. bool false
MessageLocalizer Custom handler used to override error messages in case the localization is needed. Func<ValidationMessageLocalizerEventArgs, IEnumerable<string>> null
HandlerType Forces the custom validation handler to be used while validating the values. Type null

ValidationError

Name Description Type Default
Multiline If true, shows the multiline error messages. bool false
Tooltip If true, shows the tooltip instead of label. bool false
On this page