How can we Validate Models passed from Views to our API Controllers in ASP.NET Core. Is there a tool like FluentValidation or any similar approach that can be customized to return our errors and messages back to the client apps?
2 Answers
You make use of the IValidatableObject interface. Then create a abstract base class and let your classes inherit from it. You will need to add a reference to System.ComponentModel.DataAnnotations. You can add helper methods to the base class as well.
public abstract class ValidatingBase : IValidatableObject
{
public bool IsNullOrEmpty(string property)
{
return string.IsNullOrEmpty(property);
}
#region IValidatableObject
public abstract IEnumerable<ValidationResult> Validate(ValidationContext validationContext);
public IEnumerable<ValidationResult> Validate()
{
var validationErrors = new List<ValidationResult>();
var ctx = new ValidationContext(this, null, null);
Validator.TryValidateObject(this, ctx, validationErrors, true);
return validationErrors;
}
#endregion IValidatableObject
}
Then your class that inherits from the above
public class InsertCompanies : ValidatingBase
{
public string CompanyName { get; set; }
#region ValidatingCommandBase
public override IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
if (this.IsNullOrEmpty(this.Name))
{
yield return new ValidationResult($"{nameof(this.Name)} field can't be null or empty.", new[] { nameof(this.Name) });
}
if (this.Name?.Length > 100)
{
yield return new ValidationResult($"{nameof(this.Name)} field can't be greater than 100 characters.", new[] { nameof(this.Name) });
}
}
#endregion ValidatingCommandBase
}
There is not much limitation as to what you can do with the above implementation. Perhaps it is a viable option for you?
Asp.Net Core gladly will call the method for you, more information can be found at the link below. https://docs.asp.net/en/latest/mvc/models/validation.html
Comments
[HttpPost]
public ActionResult Register(RegisterViewModel model)
{
// if the validation doesn't match then load same view again with errors
if (!ModelState.IsValid)
{
return View(model);
}
}