📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

Show me how you build a form with validation in Blazor in .NET 10. Use EditForm with DataAnnotations, add a custom rule, validate nested objects, submit to an ASP.NET Core API and show the server's validation errors next to the right fields. How does it differ when the form is rendered with static SSR?

Covers Blazor EditForm and EditContext, DataAnnotationsValidator, input components, custom validation attributes, .NET 10 nested validation, mapping ProblemDetails errors with ValidationMessageStore, and SSR forms with FormName, SupplyParameterFromForm and antiforgery.

Intermediate Coding Intermediate antiforgery blazor forms frontend problem-details validation

🎯 Key points

  • EditForm creates an EditContext that tracks field changes and validation messages
  • DataAnnotationsValidator plus ValidationMessage/ValidationSummary show attribute errors
  • Custom rules via ValidationAttribute or IValidatableObject, applied on client and server
  • In .NET 10, AddValidation() plus [ValidatableType] lets DataAnnotationsValidator validate nested objects and collections
  • Use OnValidSubmit, and map API ProblemDetails errors into a ValidationMessageStore
  • Static SSR forms need FormName and [SupplyParameterFromForm]; antiforgery token is added by EditForm and checked by UseAntiforgery
  • Client validation is UX only: the API must validate again

⏱ 30-second answer

EditForm wraps a model in an EditContext, which tracks which fields changed and holds validation messages. Add <DataAnnotationsValidator />, the built-in inputs (InputText, InputNumber, InputDate, InputSelect) and <ValidationMessage For="..." />, and handle OnValidSubmit. Custom rules are a ValidationAttribute or IValidatableObject. In .NET 10, AddValidation() with [ValidatableType] also validates nested objects and collections.

When the API rejects the request, read its ProblemDetails errors and put them into a ValidationMessageStore so they appear next to the fields. A form rendered with static SSR needs a FormName and [SupplyParameterFromForm], and antiforgery is checked by UseAntiforgery. The trade-off: client validation gives fast feedback, but only the server's validation counts.

🗣 Full answer (senior)

How I would answer this in an interview

"In Blazor the form is an EditForm bound to a model. It creates an EditContext, which tracks which fields the user touched and holds the validation messages for each field. I add DataAnnotationsValidator, use the built-in input components so they raise change notifications and get valid/invalid CSS classes, and put a ValidationMessage under each input. OnValidSubmit only runs when the model passes validation.

For single-field rules beyond [Required] and [Range], I write a ValidationAttribute. For rules that compare fields, such as an end date after a start date, I implement IValidatableObject on the model and return a ValidationResult that names the members, so the message appears under the right input. I put the request model in a shared project so the same rules run in the browser and in the API. New in .NET 10, if I call builder.Services.AddValidation() and mark the model with [ValidatableType], the validator also walks nested objects and collections, such as the address on a customer or the lines on an order. Before .NET 10 that needed a third-party validator.

The API always validates again, because client validation is just UX. When it returns a 400 with ProblemDetails, I read the errors dictionary and add each message to a ValidationMessageStore keyed by field, then call NotifyValidationStateChanged, so the server's message appears under the right input. If the page uses static SSR, the form posts back like an MVC form: it needs a unique FormName, the model gets [SupplyParameterFromForm], and the antiforgery token that EditForm renders is checked by app.UseAntiforgery(). The mistake I see is trusting the Blazor validation and skipping it on the API: anyone can post straight to the endpoint."


The pieces

Piece Job
EditForm Creates/owns the EditContext, renders <form>, raises submit events
EditContext Field state, validation messages, Validate()
DataAnnotationsValidator Runs DataAnnotations rules, per field on change and all on submit
InputText, InputNumber, InputDate, InputSelect, InputCheckbox Bind values, notify field changes, add validation CSS classes
ValidationMessage For / ValidationSummary Show messages
ValidationMessageStore Add your own messages, e.g. from the server

Where each rule goes

Rule Mechanism Runs in browser Runs on server
Required, length, pattern Attribute on shared model Yes Yes
Cross-field (dates, totals) IValidatableObject Yes Yes
Needs data (unique ABN, stock) API check → ProblemDetails No Yes
Business invariant Domain model / handler No Yes

Submit events

Event Runs when
OnValidSubmit Validation passes
OnInvalidSubmit Validation fails
OnSubmit Always; you call editContext.Validate() yourself

Interactive vs static SSR forms

Interactive (Server/WASM) Static SSR
Validation on field change Yes No; on post
Model binding Two-way binding in memory Form post bound with [SupplyParameterFromForm]
Name Optional FormName required and unique on the page
Antiforgery Token rendered, checked by middleware Same, and essential
Enhanced post (no full reload) n/a Enhance parameter on EditForm

Production example

On a supplier onboarding form with [40] fields, we shared the request records between the Blazor client and the API and mapped ProblemDetails errors into the form. Duplicate-ABN errors, which only the server can detect, started showing under the ABN field instead of a generic toast, and abandoned submissions dropped by about [25%].

🔍 What the interviewer is checking

Checks that the candidate can build a real Blazor form end to end: client validation for UX, server validation for truth, and field-level server errors.

Green flags

  • Uses EditForm, DataAnnotationsValidator and the Input* components correctly
  • Shares the request model and validates again in the API
  • Maps ProblemDetails errors into a ValidationMessageStore
  • Knows SSR forms need FormName, [SupplyParameterFromForm] and antiforgery

Red flags

  • Treats client validation as security
  • Shows every server error as a generic message
  • Does not know how nested objects are validated

📚 Learn in depth

1. How EditContext works

InputText (Value, ValueChanged, ValueExpression)
   -> user types -> ValueChanged -> model property set
   -> EditContext.NotifyFieldChanged(FieldIdentifier)
   -> OnFieldChanged event -> DataAnnotationsValidator validates that field
   -> ValidationMessageStore updated -> OnValidationStateChanged
   -> ValidationMessage components re-render

A FieldIdentifier is (model object, property name). That is why For="() => model.Email" takes an expression: Blazor extracts the object and property from it to find the right messages.

2. Message stores

Each validator owns a ValidationMessageStore. The EditContext reports the union of all stores. Server errors go in your own store, which you clear when the user edits that field, otherwise a stale "email already used" message sticks after they fix it.

3. Nested validation in .NET 10

DataAnnotations on its own validates only the top-level object's properties. .NET 10 adds a source-generated validation system (the same one Minimal APIs use). You call AddValidation() and mark a top-level type with [ValidatableType]; the generator discovers nested types and collection items, and DataAnnotationsValidator uses it. At the time of writing, the attribute lives in an experimental namespace, so the compiler emits an experimental warning you suppress deliberately.

4. Mapping ProblemDetails

ASP.NET Core's ValidationProblemDetails returns errors as { "Email": ["..."], "Lines[0].Quantity": ["..."] }. Top-level keys map directly to new FieldIdentifier(model, key). Nested keys need you to resolve the path to the nested object; many teams map top-level keys to fields and show the rest in the summary.

If the API serialises with camelCase dictionary keys, email will not match the C# property Email; compare case-insensitively.

5. Static SSR forms

Without a circuit, the browser posts the form. The framework finds the handler by FormName (the _handler field), binds form fields into the [SupplyParameterFromForm] property, runs the component again and executes OnValidSubmit on the server. EditForm renders an <AntiforgeryToken />, and UseAntiforgery() (after authentication and authorisation) rejects posts without a valid token. Phase 14 covers CSRF itself.

Try it yourself

  1. Build the form below, type an invalid email and watch the invalid CSS class appear on blur.
  2. Return a 400 ProblemDetails from the API for a duplicate email and see it appear under the field.
  3. Add an address object without AddValidation(), see nested errors ignored, then turn it on.
  4. Remove FormName from a static SSR form and read the error.
  5. Post to the SSR form with curl without the antiforgery token and confirm the 400.

💻 Code

A shared request model, the API endpoint, and the Blazor form that shows both client and server errors.

// Shared/CreateCustomer.cs (referenced by the API and the Blazor client)
using System.ComponentModel.DataAnnotations;
using Microsoft.Extensions.Validation;

namespace Shop.Shared;

#pragma warning disable ASP0029 // ValidatableType is experimental in .NET 10
[ValidatableType]
#pragma warning restore ASP0029
public sealed class CreateCustomer
{
    [Required, StringLength(100)] public string Name { get; set; } = "";
    [Required, EmailAddress] public string Email { get; set; } = "";
    [Required, Abn] public string Abn { get; set; } = "";
    public Address Address { get; set; } = new(); // nested: validated in .NET 10
}

public sealed class Address
{
    [Required] public string Street { get; set; } = "";
    [Required, RegularExpression(@"^\d{4}$", ErrorMessage = "Postcode must be 4 digits.")]
    public string Postcode { get; set; } = "";
}

// Custom rule: 11 digits (checksum omitted for brevity)
public sealed class AbnAttribute : ValidationAttribute
{
    protected override ValidationResult? IsValid(object? value, ValidationContext ctx) =>
        value is string s && s.Replace(" ", "").Length == 11 && s.Replace(" ", "").All(char.IsDigit)
            ? ValidationResult.Success
            : new ValidationResult("Enter an 11-digit ABN.", [ctx.MemberName!]);
}
// API Program.cs: validates again and returns ValidationProblemDetails
builder.Services.AddValidation(); // .NET 10 Minimal API validation

app.MapPost("/api/customers", async (CreateCustomer req, ICustomerStore store, CancellationToken ct) =>
{
    if (await store.AbnExistsAsync(req.Abn, ct))
        return Results.ValidationProblem(new Dictionary<string, string[]>
        {
            [nameof(CreateCustomer.Abn)] = ["A customer with this ABN already exists."]
        });

    var id = await store.AddAsync(req, ct);
    return Results.Created($"/api/customers/{id}", new { id });
});
@* NewCustomer.razor (interactive) *@
@page "/customers/new"
@rendermode InteractiveServer
@inject HttpClient Http
@inject NavigationManager Nav

<EditForm EditContext="editContext" OnValidSubmit="SubmitAsync">
    <DataAnnotationsValidator />
    <ValidationSummary />

    <label>Name <InputText @bind-Value="model.Name" /></label>
    <ValidationMessage For="() => model.Name" />

    <label>Email <InputText @bind-Value="model.Email" type="email" /></label>
    <ValidationMessage For="() => model.Email" />

    <label>ABN <InputText @bind-Value="model.Abn" /></label>
    <ValidationMessage For="() => model.Abn" />

    <label>Postcode <InputText @bind-Value="model.Address.Postcode" /></label>
    <ValidationMessage For="() => model.Address.Postcode" />

    <button type="submit" disabled="@saving">Save</button>
</EditForm>

@code {
    private readonly CreateCustomer model = new();
    private EditContext editContext = default!;
    private ValidationMessageStore serverErrors = default!;
    private bool saving;

    protected override void OnInitialized()
    {
        editContext = new EditContext(model);
        serverErrors = new ValidationMessageStore(editContext);
        // Clear a server message as soon as the user edits that field
        editContext.OnFieldChanged += (_, e) => serverErrors.Clear(e.FieldIdentifier);
    }

    private async Task SubmitAsync()
    {
        saving = true;
        serverErrors.Clear();
        try
        {
            var response = await Http.PostAsJsonAsync("api/customers", model);
            if (response.IsSuccessStatusCode) { Nav.NavigateTo("/customers"); return; }

            var problem = await response.Content.ReadFromJsonAsync<HttpValidationProblemDetails>();
            foreach (var (key, messages) in problem?.Errors ?? new Dictionary<string, string[]>())
            {
                // Keys may be camelCase; match properties case-insensitively
                var prop = typeof(CreateCustomer).GetProperties()
                    .FirstOrDefault(p => p.Name.Equals(key, StringComparison.OrdinalIgnoreCase));
                var field = prop is null ? new FieldIdentifier(model, string.Empty) : new FieldIdentifier(model, prop.Name);
                serverErrors.Add(field, messages);
            }
            editContext.NotifyValidationStateChanged();
        }
        finally { saving = false; }
    }
}

⚠ Common mistakes

  • Mistake: Validating only in Blazor. Why it is wrong: anyone can call the API directly, and WebAssembly code can be modified. Instead: validate again in the API with the same shared model.
  • Mistake: Using plain <input @bind> instead of InputText. Why it is wrong: plain inputs do not notify the EditContext, so per-field validation and CSS classes do not work. Instead: use the Input* components or call NotifyFieldChanged.
  • Mistake: Showing server errors in a toast. Why it is wrong: users cannot tell which field to fix. Instead: map ProblemDetails errors into a ValidationMessageStore.
  • Mistake: Never clearing server messages. Why it is wrong: the error stays after the user fixes the value. Instead: clear that field's messages in OnFieldChanged.
  • Mistake: Expecting nested objects to be validated by default before .NET 10. Why it is wrong: DataAnnotations validates only top-level properties. Instead: in .NET 10 use AddValidation() with [ValidatableType].
  • Mistake: Putting cross-field rules (end date after start date) in a property attribute. Why it is wrong: a single-property attribute cannot see the other field cleanly. Instead: implement IValidatableObject.Validate and return a ValidationResult naming the affected members.
  • Mistake: A static SSR form without FormName or with [Parameter] instead of [SupplyParameterFromForm]. Why it is wrong: the post cannot be routed or bound. Instead: give each form a unique FormName and use [SupplyParameterFromForm].
  • Mistake: Allowing double submits. Why it is wrong: two records get created. Instead: disable the button while saving and make the API idempotent.
  • Mistake: No tests for the validation rules. Why it is wrong: a renamed property or changed attribute silently breaks the client, the server or the error mapping. Instead: unit-test the model with Validator.TryValidateObject, test the endpoint's 400 response with WebApplicationFactory, and test the form with bUnit.

🏛 Senior insight: trade-offs

The senior decision is where each rule lives. Format rules (required, length, pattern) go on a shared request model so the browser and API agree. Rules needing data (duplicate ABN, credit limit) live only on the server and come back as ProblemDetails mapped to fields. Business invariants belong in the domain, not in attributes.

Approach When it fits Cost When not to
DataAnnotations on a shared model Most LOB forms Limited to attribute-style rules Complex cross-field logic
IValidatableObject Cross-field rules on one model Runs only after attributes pass Rules needing a database
FluentValidation with a Blazor adapter Large rule sets, team already uses it Extra library, adapter to maintain Simple forms (.NET 10 covers nesting now)
Server-only checks mapped to fields Uniqueness, permissions, stock One round trip Format checks the client can do

I measure form quality by submit failure rate and field-level error counts in Application Insights custom events.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate says the API validates the same model again Why: Checks how they validate on the server: DataAnnotations, FluentValidation and the .NET 10 Minimal API validation
    How to answer

    I validate input at the edge and business rules in the application or domain layer. For input, DataAnnotations ([Required], [Range], [StringLength]) and IValidatableObject on request DTOs are the baseline. In controllers, binding fills ModelState and [ApiController] returns a 400 ValidationProblemDetails before the action runs. In Minimal APIs on .NET 10, builder.Services.AddValidation() uses a source generator to validate parameters and return the same 400 ProblemDetails; before .NET 10 you needed a filter. FluentValidation is my choice for complex, conditional or async rules; I call it explicitly or from a filter, because its automatic MVC integration is deprecated. Business rules like stock levels or uniqueness are checked where the data lives and returned in the same error shape. The trade-off: attributes are simple and visible in OpenAPI; code-based validators are more expressive.

  2. When: Candidate maps ProblemDetails errors to fields Why: Checks whether they can do the same in a React + TypeScript client for a full-stack role
    How to answer

    On the server, a Minimal API with .NET 10's built-in validation (AddValidation() plus DataAnnotations on the request record) returns 400 ValidationProblemDetails automatically and 201 Created with the new DTO on success.

    On the client, a small typed API module wraps fetch: it checks res.ok, parses ProblemDetails into a typed ApiError with the errors dictionary, and returns typed DTOs. The React screen uses TanStack Query: useQuery for the list and useMutation for the create, then invalidates the list so it refetches.

    The form shows field errors from the server next to each input, a general message for non-field problems, and disables submit while saving. Client checks are only for speed of feedback; the trade-off is a little duplication for a much better UX, with the server as the source of truth.

  3. When: Candidate disables the submit button while saving Why: Checks whether they know a disabled button does not prevent duplicates and the API must be idempotent
    How to answer

    Disabling the button only stops the common case; retries, two tabs or a flaky network can still send the request twice. Make the write idempotent: the client generates an idempotency key (a GUID) when the form is opened or first submitted and reuses the same key on every retry of that submission, sending it in an Idempotency-Key header. The API inserts the key and the result in the same database transaction as the create, protected by a unique constraint, and returns the stored response for repeats (a concurrent duplicate that loses the race gets 409 or waits and replays). A natural unique key such as the SKU adds a second guard. Keys carry a TTL (for example 24 hours) and a scheduled job deletes expired rows. For UX, the client treats a replayed response as success and shows the saved record, so the user never sees 'already exists'.

More in Blazor

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me