MVC
already does the automatic model validation for you. To get the errors of your model you can access the ModelState
property. Example:
var errors = string.join(" ", ModelState.SelectMany(s => s.Value.Errors)
.Select(e => e.ErrorMessage))
if(errors.Length > 0){
return BadRequest(errors);
}
To display user-friendly messages you must set the ErrorMessage
property to its validation attributes in your template. Example:
public class Modelo {
[StringLength(1, ErrorMessage = "Introduza um nome válido")]
public string Name{get;set;}
}
If this is not enough for you. You can always validate the model programmatically to know what the errors are. Example:
var context = new ValidationContext(model, null, null);
var results = new List<ValidationResult>();
bool valid = Validator.TryValidateObject(model, context, results, true);
if (valid)
{
return Task.CompletedTask;
}
var errors = string.Join(" ", results.Select(e => e.ErrorMessage));
throw new InvalidOperationException($"Can not insert because data is not valid. {errors}");