Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
.NET Core Web API - Model Validations using Built-In Attribute
// Employee.cs - Model with validation attributes
public class Employee
[StringLength(maximumLength: 250, MinimumLength = 10)]
public string Name { get; set; }
[EmailAddress(ErrorMessage = "Email address is not valid.")]
public string Email { get; set; }
[Phone(ErrorMessage = "Phone is not valid.")]
public string Phone { get; set; }
[Range(minimum: 30, maximum: 400,
ErrorMessage = "Hourly salary does not fall within allowed range.")]
public decimal HourlySalary { get; set; }
// EmployeeController.cs - API Controller
public class EmployeeController : ControllerBase
public Employee Post([FromBody] Employee employee)
// No need to check ModelState.IsValid
// Automatic HTTP 400 is returned in case of validation errors
// If model is valid, incoming data is returned as response.
return employee;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment