Form validation — MVC
Project FormValidation.Mvc · the same registration form in three ways.
The three approaches
Q & A
-
Where are the validation rules defined?
Frontend: in the HTML (attributes).
Backend / both: inModels/Registration.cs(Data Annotations). -
How are they linked to the form?
Frontend:name="…"on inputs.
Backend / both: tag helpersasp-for. -
How is it validated on the frontend?
Demo 1: browser HTML5.
Demo 3: jQuery Validate + jquery.validate.unobtrusive (see next question). -
How is it validated on the backend?
Model binding → annotations →ModelState→if (!ModelState.IsValid)in the controller. -
How is form data bound to the C# model?
Action parameterRegistration model(demo 1: separate parameters). Matching on form-fieldname↔ property name. -
What does “unobtrusive” validation mean?
Validation logic is not written as custom JavaScript next to every field. Instead:- Rules live in C# as Data Annotations on
Registration. - Tag helpers (
asp-for) emit them into HTML asdata-val-*attributes (e.g.data-val-required="Name is required"). jquery.validate.unobtrusivereads those attributes and wires upjquery.validate.- The browser shows errors before submit — without a round-trip and without per-field JS you wrote yourself.
ModelState). - Rules live in C# as Data Annotations on