I would like to know what is the best way to validate a model before saving it and the pros and cons. I'm in doubt between service layer and IValidatableObject.
Service layer:
public class PersonService
{
public void Insert(Person person)
{
if (!IsValid(person))
{
//something
}
}
}
IValidatableObject:
public class Person:IValidatableObject
{
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
if (!IsValid(this))
{
//something
}
}
}
IValidatableObject
is typically used to self-validate the entity, i.e. validation is restricted to checking the properties of Person
.
Self validation (e.g. IValidatableObject
and DataAnnotations) are useful for the 'initial' checking, e.g. on user interfaces, to ensure that a user has filled in all required fields, and broadly meets validation rules like regex matches, string lengths, date ranges etc.
In order to keep your Person
entity decoupled from the rest of your system, you wouldn't be able to do more advanced business rules in Self Validation which required round trips to your database, or used service calls to external systems.
In contrast, validation done on a Service / Business / Manager Layer is usually used as part of a transaction, e.g. Inserting / Updating / State Transitions, and this can do more involved validation, e.g.
Person
entity (i.e. fetch related data from the database, consume other web services etc, when making validation decisions). An example here would be to determine whether a bank account has any funds available, or whether more than 10 withdrawals were made in a day.person.Validate()
) (including using IValidatableObject
) to prevent duplicating rules.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With