In this case, your choice = System.ComponentModel.DataAnnotations
Roughly speaking, it is a set of predefined attributes that can describe the constraints for each property in a class that describes a data model. There is a set of predefined constraints (ex. RequiredAttribute, MaxLengthAttribute, EmailAttribute, ReqularExpressionAttribute ...). In addition, it is possible to create your own custom attributes, inheriting from the basic interface. You can also add your own validation error message to any attribute.
public class CreditCardStandartInfo { [Required] [RegularExpression("^[0-9]{16}$", ErrorMessage = "incorrect format")] public string CardNumber { get; set; } [Required] [MinLength(6)] public string CardholderName { get; set; } [Required] [RegularExpression("^[0-9]{3}$", ErrorMessage = "incorrect format")] public string CVVCode { get; set; } [Required] public virtual int ExpireMonth { get; set; } [Required] public virtual int ExpireYear { get; set; } }
If you use the EF CodeFirst, you can attach attributes directly to the data model. And EF automatically validates them during validation.
If you have ModelFirst (there is no direct access to entity classes), then I suggest adding a layer of DTO objects and imposing attributes on them. And carry out the verification yourself. For this I propose to use the following code:
public static class DataAnnotationsValidator { public static bool TryValidate(object instance, out ICollection<ValidationResult> results) { var context = new ValidationContext(instance, serviceProvider: null, items: null); results = new List<ValidationResult>(); return Validator.TryValidateObject( instance, context, results, validateAllProperties: true ); } }
If errors are found, you will receive a list of them that you provide to the client. If validation succeeds, you copy data from your DTO objects to the EF entity and perform the necessary operations from the database.