One of the most crucial steps in creating web apps that are ready for production is validation. Inadequate validation could result in users submitting malicious, erroneous, or incomplete data, which could cause logic errors, inconsistent business processes, database corruption, and security flaws. A built-in model validation framework for Razor pages, controllers, and basic APIs is offered by ASP.NET Core. For complicated real-world scenarios, it is built on attributes, reusable rules, and optional custom logic. Validation ensures that the backend does not trust frontend data blindly, even if Angular, React, or Blazor already perform client-side checks.
This article examines how model validation works in real-life enterprise development with step-by-step implementation, examples, and best practices.
Problem Statement in the Real World
A freight booking web application was developed by a logistics company. Users could submit shipment weight, dimensions, pick-up date, and client information using their front-end user interface. At first, validation was limited to Angular, presuming that backend security was not required.
Within three months:
- Incorrect data formats reached the database.
- Some required fields were missing because users bypassed validation using developer tools.
- Negative weight values caused pricing miscalculations.
- Fake customer emails made automated notifications fail.
After an internal audit, the engineering team implemented server-side validation using ASP.NET Core Model Validation.
How Model Validation Works in ASP.NET Core
- When a request is received, ASP.NET Core automatically attempts to bind request data to the model.
- Validation attributes defined on properties are checked.
- If validation fails, the request is immediately blocked.
- An appropriate error response is returned (usually 400 Bad Request).
- The controller method does not execute until the data is valid.
This approach ensures backend consistency even if client-side validation is bypassed.
Basic Example Model with Required and Range Validation
public class BookingRequest
{
[Required(ErrorMessage = "Customer Name is required.")]
public string CustomerName { get; set; }
[Required]
[EmailAddress(ErrorMessage = "Invalid email format.")]
public string Email { get; set; }
[Range(1, 10000, ErrorMessage = "Weight must be between 1 and 10000 kg.")]
public decimal Weight { get; set; }
[Required]
public DateTime PickupDate { get; set; }
}
Controller Example
[ApiController]
[Route("api/[controller]")]
public class BookingController : ControllerBase
{
[HttpPost("create")]
public IActionResult CreateBooking([FromBody] BookingRequest request)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
return Ok("Booking Created Successfully");
}
}
Custom Validation Attribute Example
Real-world systems require rules beyond simple range or required fields. For example: block booking on weekends.
public class NoWeekendAttribute : ValidationAttribute
{
public override bool IsValid(object value)
{
if (value is DateTime date)
{
return date.DayOfWeek != DayOfWeek.Saturday &&
date.DayOfWeek != DayOfWeek.Sunday;
}
return false;
}
}
Apply it:
[NoWeekend(ErrorMessage = "Pickup date cannot be on weekends.")]
public DateTime PickupDate { get; set; }
Adding Cross-Field Validation Using IValidatableObject
Some business rules depend on multiple fields. Example: insured shipment requires a declared value.
public class Shipment : IValidatableObject
{
public bool IsInsured { get; set; }
public decimal? DeclaredValue { get; set; }
public IEnumerable<ValidationResult> Validate(ValidationContext context)
{
if (IsInsured && DeclaredValue == null)
{
yield return new ValidationResult(
"Declared value is required for insured shipments.",
new[] { nameof(DeclaredValue) }
);
}
}
}
Validation in Minimal APIs (ASP.NET Core 7+)
app.MapPost("/shipment", (Shipment shipment) =>
{
if (!MiniValidator.TryValidate(shipment, out var errors))
return Results.ValidationProblem(errors);
return Results.Ok("Shipment processed");
});
Best Practices
- Never rely solely on client-side validation.
- Use meaningful validation messages.
- Encapsulate reusable logic in custom attributes.
- Use IValidatableObject only when cross-field logic is required.
- Version validation rules if business logic evolves.
- Log validation failures for auditing.
Common Mistakes to Avoid
| Mistake | Why It Is Wrong |
|
Only validating on frontend
|
Can be bypassed using tools like Postman
|
|
Hardcoding business rules in controllers
|
Makes code hard to maintain
|
|
Generic validation messages
|
Users cannot understand the issue
|
|
Returning 200 OK with validation errors
|
Breaks API contract
|
Testing Validation
Use Postman or unit tests to verify behavior.
Example Unit Test
[Test]
public void Booking_ShouldFail_WhenWeightIsNegative()
{
var model = new BookingRequest { Weight = -5 };
var context = new ValidationContext(model);
var results = new List<ValidationResult>();
var isValid = Validator.TryValidateObject(model, context, results, true);
Assert.IsFalse(isValid);
}
Final Recommendations
- Treat validation as part of the domain model, not just a UI feature.
- Keep validation rules consistent across systems.
- Validate early, validate everywhere, validate before storing data.
Conclusion
ASP.NET Core model validation is robust and adaptable. Your web application can handle data safely and consistently by using cross-property validation, custom rules, and built-in attributes. Validation lowers support requests, prevents damaged data, and increases program reliability in business settings. Validation of models is more than a feature. It is a precaution that keeps your system safe against deliberate abuse, automation mistakes, and human error.
European Best, cheap and reliable ASP.NET Core 10.0 hosting with instant activation. HostForLIFE.eu is #1 Recommended Windows and ASP.NET hosting in European Continent. With 99.99% Uptime Guaranteed of Relibility, Stability and Performace. HostForLIFE.eu security team is constantly monitoring the entire network for unusual behaviour. We deliver hosting solution including Shared hosting, Cloud hosting, Reseller hosting, Dedicated Servers, and IT as Service for companies of all size.
