I came across this page for model validation and found validation attributes pretty amazing. But it looks very geared towards the web and I believe it only works when deserializing.
What would be the equivalent/idiomatic way to validate objects when initializing and throughout the object's lifetime? Or maybe I can use validation attributes but just couldn't find the non-ASP docs?
You can try using Validator.TryValidateObject
with manually created ValidationContext
:
var someObjectToValidate = ...;
var vc = new ValidationContext(someObjectToValidate, serviceProvider: null, items: null);
var results = new List<ValidationResult>();
bool isValid = Validator.TryValidateObject(u, vc, results, true);
But personally I prefer using FluentValidation package which can be integrated with ASP.NET Core.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.