Form validation — MVC

Project FormValidation.Mvc · the same registration form in three ways.

The three approaches

1. Frontend

HTML5 (required, type="email", …). Server does not check.

Open

2. Backend

Data Annotations + ModelState. No client scripts (novalidate).

Open

3. Both

Annotations → data-val-* → unobtrusive validation; server still checks.

Open

Q & A

  1. Where are the validation rules defined?
    Frontend: in the HTML (attributes).
    Backend / both: in Models/Registration.cs (Data Annotations).
  2. How are they linked to the form?
    Frontend: name="…" on inputs.
    Backend / both: tag helpers asp-for.
  3. How is it validated on the frontend?
    Demo 1: browser HTML5.
    Demo 3: jQuery Validate + jquery.validate.unobtrusive (see next question).
  4. How is it validated on the backend?
    Model binding → annotations → ModelState → if (!ModelState.IsValid) in the controller.
  5. How is form data bound to the C# model?
    Action parameter Registration model (demo 1: separate parameters). Matching on form-field name ↔ property name.
  6. What does “unobtrusive” validation mean?
    Validation logic is not written as custom JavaScript next to every field. Instead:
    1. Rules live in C# as Data Annotations on Registration.
    2. Tag helpers (asp-for) emit them into HTML as data-val-* attributes (e.g. data-val-required="Name is required").
    3. jquery.validate.unobtrusive reads those attributes and wires up jquery.validate.
    4. The browser shows errors before submit — without a round-trip and without per-field JS you wrote yourself.
    So one rule set (backend) is reused on the frontend. That is still only UX: the server must check again (demo 3 still uses ModelState).