any one tell that how to validate in Model in web api core using data annotation?
Loading
any one tell that how to validate in Model in web api core using data annotation?
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
Sandhiya PriyaRank #26 · 43.2K reputationPosted Nov 19, 2025, 11:04 PM EST
1. Add Data Annotation Attributes in Your Model
ASP.NET Core automatically validates these before entering your controller action.
Example Model
public class RegisterRequest { [Required(ErrorMessage = "Username is required")] [StringLength(20, MinimumLength = 3)] public string Username { get; set; } [Required] [EmailAddress(ErrorMessage = "Invalid Email format")] public string Email { get; set; } [Required] [MinLength(6, ErrorMessage = "Password must be at least 6 characters")] public string Password { get; set; } [Range(18, 60, ErrorMessage = "Age must be between 18 and 60")] public int Age { get; set; } }2. Validate in Controller Using ModelState
ASP.NET Core automatically populates ModelState.
[HttpPost("register")] public IActionResult Register([FromBody] RegisterRequest model) { if (!ModelState.IsValid) { return BadRequest(ModelState); // returns all validation errors } return Ok("Registration successful"); }3. Enable Automatic Validation (Built-in in ASP.NET Core 3+)
From .NET Core 3 and above, automatic model validation is enabled by default.
Meaning:
1. You don't need to manually check
ModelState.IsValid2. The framework returns 400 BadRequest with validation errors automatically.
But if you prefer manual checking (recommended for custom responses), use the previous method.
4. Optional: Customize Validation Response
If you want cleaner error messages:
if (!ModelState.IsValid) { var errors = ModelState.Values .SelectMany(v => v.Errors) .Select(e => e.ErrorMessage) .ToList(); return BadRequest(new { Success = false, Errors = errors }); }Bonus: Custom Validation Attribute Example
public class NoSpaceAttribute : ValidationAttribute { public override bool IsValid(object value) { if (value == null) return true; return !value.ToString().Contains(" "); } }Use it like:
[NoSpace(ErrorMessage = "Username cannot contain spaces")] public string Username { get; set; }Summary