xam86
xam86

Reputation: 121

Blazor app, how to add model state validation error?

How do I add a custom validation message in the SaveItem event (prefer not to use data annotations)? It should show up in the "ValidationMessage For=" context.

@using System.ComponentModel.DataAnnotations
@page "/edititem"


<EditForm Model="@model" OnSubmit="@Submit" OnValidSubmit="@SaveItem">
    <DataAnnotationsValidator />
    <ValidationSummary />

    <InputText id="ItemName" @bind-Value="@model.ItemName" />
    <ValidationMessage For="@(() => model.ItemName)" />
    <button type="submit">Submit</button>
</EditForm>

@code {
    ItemModel model = new ItemModel();

    private void Submit()
    {

    }
    private void SaveItem()
    {


    }

    public class ItemModel
    {
        [Required]
        public string ItemName{ get; set; }
    }
}

Upvotes: 10

Views: 6690

Answers (2)

Giovanni Romio
Giovanni Romio

Reputation: 1056

<EditForm EditContext="editContext" OnSubmit="@Submit" 
     OnValidSubmit="@SaveItem">
    <DataAnnotationsValidator />
    <ValidationSummary />
    <InputText id="ItemName" @bind-Value="@model.ItemName" />
    <ValidationMessage For="@(() => model.ItemName)" />
    <button type="submit">Submit</button>
</EditForm>

@code {
    private EditContext? editContext;
    private ValidationMessageStore? messageStore;
    ItemModel model = new ItemModel();

    protected override void OnInitialized()
    {
        editContext = new EditContext(model);

        messageStore = new(editContext);
    }

    private void Submit()
    {

    }
    private void SaveItem()
    {
        messageStore.Add(() => model.ItemName, "ItemName invalid");
    }

    public class ItemModel
    {
        [Required]
        public string ItemName{ get; set; }
    }
}

To achieve custom validation outside data-attributes follow those 3 steps:

  1. Declare an EditContext and a ValidationMessageStore objects in your page;
  2. Bind your form to the EditContext instance (in your case you have to remove the Model attribute);
  3. Perform custom validation and display the error adding an item to the messageStore object;

Upvotes: 5

You can add custom validation in server side by add some Component which contain error message. Display validation error from the server

Upvotes: 1

Related Questions