Form handling in ASP.NET Core MVC involves creating models, binding them to forms in views, and validating input. Data Annotations are attributes you apply to model properties to enforce validation rules. They simplify server-side validation and can also trigger client-side validation using unobtrusive JavaScript.
📦 Common Data Annotation Attributes
Attribute | Description |
---|---|
[Required] |
Field must not be empty. |
[StringLength] |
Sets maximum (and optionally minimum) string length. |
[Range] |
Limits a numeric value range. |
[EmailAddress] |
Validates email format. |
[Compare] |
Compares two properties (e.g., Password/Confirm). |
[RegularExpression] |
Validates format with a regex pattern. |
[DataType] |
Specifies type like DataType.Date , Password . |
[Display] |
Sets a friendly name for the UI. |
🧱 Example: Model with Data Annotations
🧩 Razor View: Form with Validation
✅ Controller Action
⚙️ Enable Client-Side Validation
Make sure these are included in your _Layout.cshtml
or view:
This loads the required jQuery validation libraries via the built-in partial.
🧪 Validation Summary
-
✅ Data Annotations are declarative and simple to use.
-
✅ Validation happens on both client and server.
-
⚠️ Always validate on the server — client-side validation can be bypassed.
-
🔄 Combine with
ModelState.IsValid
to ensure data integrity. -