Blazor Form

Blazor Form is a powerful component that empowers developers to create interactive and highly customizable forms with ease. Whether you are building a simple contact form or a complex data entry system, Blazor Form provides the tools you need to manage input states, validate user input, and define actions based on form validity.

Features:

JavaScript Independence: This component operates seamlessly without requiring JavaScript, offering a lightweight and straightforward solution.

Appearance customization: Customizable styles and themes.

Rendering options: Render your component as various HTML tags for maximum flexibility and integration.

Learn about core component featuresLearn about input component features

Dynamic Validation Triggers

Blazor Form supports both field-level validation triggered by changes in individual input fields and form-level validation triggered upon form submission. This flexibility ensures that you can validate user input in real-time as they interact with your form or when they attempt to submit it.

Submission Validation (Validate on Form Submit):

This type of validation occurs when the user attempts to submit the entire form. In this case, the system checks the validity of all the input fields collectively before allowing the form to be submitted. It's like a final check before the user's data is processed. You can also call it "final validation" or "form-wide validation."

<BlazorForm ValidationType="ValidationType.OnSubmit">
    <BlazorLabel for="my-username-input">Username (required)</BlazorLabel>
    <BlazorInputText id="my-username-input" UpdateOnHtmlEvent="oninput" @bind-Value="Username" />
    <BlazorValidationMessage For="() => Username" />
    <BlazorButton Variants="new[] {BaseVariants.Success}" type="submit">Submit</BlazorButton>
</BlazorForm>

@code {
    [Display(Name = "Username")]
    [Required]
    public string Username { get; set; } = "BlazorSchool";
}
Dynamic Validation (Validate on Field Change):

This approach refers to real-time validation of individual input fields as the user interacts with them. Essentially, it means that as the user types or selects values in the form, the system checks and provides feedback on the validity of each field immediately. You can think of it as "live validation" or "instant feedback".

<BlazorForm ValidationType="ValidationType.AfterFieldChange">
    <BlazorLabel for="my-firstname-input">FirstName (required)</BlazorLabel>
    <BlazorInputText id="my-firstname-input" UpdateOnHtmlEvent="oninput" @bind-Value="FirstName" />
    <BlazorValidationMessage For="() => FirstName" />
</BlazorForm>

@code {
    [Display(Name = "First Name")]
    [Required]
    public string FirstName { get; set; } = "Joseph";
}

Custom Validation Logic & Input State Management

Blazor Form provides the flexibility to inject custom validation logic into your forms. This means you can implement bespoke validation rules tailored to your application's specific requirements. It also enables developers to effortlessly access and modify the state of form inputs. This capability ensures that you have full control over how user inputs are processed and displayed within your application.

<BlazorForm OnValidationCalled="ValidateProductForm">
    <BlazorLabel>
        Product Name (type 'BlazorLibrary' to pass validation)
        <BlazorInputText @bind-Value="ProductName" FieldState="ProductNameState" UpdateOnHtmlEvent="oninput" />
        <div>Is Modified: @ProductNameState.IsModified</div>
    </BlazorLabel>
    <BlazorValidationMessage For="() => ProductName" />
    <BlazorButton Variants="new[] {BaseVariants.Success}" type="submit">Submit</BlazorButton>
</BlazorForm>

@code {
    public string ProductName { get; set; } = "";
    public FieldState ProductNameState { get; set; } = new();

    public void ValidateProductForm()
    {
        string messageId = "ProductNameState_Not_BlazorLibrary";
        ProductNameState.Messages.Remove(messageId);

        if (ProductName != "BlazorLibrary")
        {
            ProductNameState.Messages.Add(new ValidationMessage(messageId, ValidationMessageType.Error, "The product name must be 'BlazorLibrary'"));
        }
    }
}

Message Display

Blazor Form includes a message display feature that allows developers to show various types of messages to users. These message types include:

  • Success: For conveying successful operations or actions.
  • Info: For providing informative messages to users.
  • Warning: To highlight important information or warnings.
  • Error: To display error messages or alerts.
<BlazorForm OnValidationCalled="ValidateQuantityForm">
    <BlazorLabel>
        Quantity (input negative number to see error message, input number &lt;3 to see warning message)
        <BlazorInputNumber @bind-Value="Quantity" FieldState="QuantityState" />
    </BlazorLabel>
    <BlazorValidationMessage For="() => Quantity" />
    <BlazorButton Variants="new[] {BaseVariants.Success}" type="submit">Submit</BlazorButton>
</BlazorForm>

@code {
    [Range(0, int.MaxValue,ErrorMessage = "Invalid quantity")]
    public int Quantity { get; set; } = 0;
    public FieldState QuantityState { get; set; } = new();

    public void ValidateQuantityForm()
    {
        string warningMessageId = "Discount_Could_Be_Applied";
        string successMessageId = "Discount_Has_Been_Applied";
        QuantityState.Messages.Remove(warningMessageId, successMessageId);

        if (Quantity < 3)
        {
            QuantityState.Messages.Add(new(warningMessageId, ValidationMessageType.Warning, "Buy 3 items for the discounted price."));
        }

        if (Quantity >= 3)
        {
            QuantityState.Messages.Add(new(successMessageId, ValidationMessageType.Success, "Discounted price applied."));
        }
    }
}
Sorting & Templating Display Message

Blazor Form offers versatile options for sorting and customizing the display of messages within your application. Messages can be categorized by type and presented using customizable templates, allowing you to create a tailored messaging system to enhance the user experience. See Validation Message to learn more.

DataAnnotation Attribute Validation

Leverage the power of DataAnnotation attributes to validate form fields effortlessly. With Blazor Form, you can annotate your data models with attributes like [Required], [StringLength], and more to enforce data validation rules.

<BlazorForm>
    <BlazorLabel>
        Password (4-8 characters)
        <BlazorInputPassword @bind-Value="Password" UpdateOnHtmlEvent="oninput" />
    </BlazorLabel>
    <BlazorValidationMessage For="() => Password" />
    <BlazorButton Variants="new[] {BaseVariants.Success}" type="submit">Submit</BlazorButton>
</BlazorForm>

@code {
    [MinLength(4, ErrorMessage = "The password length must between 4-8 characters.")]
    [MaxLength(8, ErrorMessage = "The password length must between 4-8 characters.")]
    public string Password { get; set; } = "";
}

Form Validation Actions

Define actions to be executed when a form becomes valid or invalid. This feature allows you to seamlessly integrate behaviors such as enabling/disabling submit buttons or providing feedback to users based on the form's validation status.

<div>@Message</div>
<BlazorForm OnValidSubmit="ValidSubmit" OnInvalidSubmit="InvalidSubmit">
    <BlazorLabel>
        <BlazorInputCheckbox @bind-Value="Accept" />
        I have read and accept the agreement.
    </BlazorLabel>
    <BlazorButton Variants="new[] {BaseVariants.Success}" type="submit">Submit</BlazorButton>
</BlazorForm>

@code {
    [Range(typeof(bool), "true", "true")]
    public bool Accept { get; set; } = false;
    public string Message { get; set; } = "";

    public void ValidSubmit() => Message = "Submitted";
    public void InvalidSubmit() => Message = "Form contains invalid value.";
}

Parameters

BlazorForm

Name Type Description
RenderAs string Specifies the HTML tag to be used for rendering the component. This can be any valid HTML tag, such as div, span, button, or other suitable tags.
ValidationType ValidationType Specify the trigger of the validation for the form.
OnValidationCalled EventCallback Inject custom validation logic.
OnValidSubmit EventCallback The callback when the form is valid.
OnInvalidSubmit EventCallback The callback when the form is invalid.
An error has occurred. This application may no longer respond until reloaded. Reload 🗙