Last active
November 25, 2018 22:00
-
-
Save wellingtonjhn/bd7d786b975b09b0e258607f1b0f50f5 to your computer and use it in GitHub Desktop.
Entity with Validator Sample
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| public abstract class Entity | |
| { | |
| public Guid Id { get; protected set; } | |
| public bool Valid { get; private set; } | |
| public bool Invalid => !Valid; | |
| public ValidationResult ValidationResult { get; private set; } | |
| public bool Validate<TModel>(TModel model, AbstractValidator<TModel> validator) | |
| { | |
| ValidationResult = validator.Validate(model); | |
| return Valid = ValidationResult.IsValid; | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| public class Customer : Entity | |
| { | |
| public string Name { get; } | |
| public string Email { get; } | |
| public Customer(string name, string email) | |
| { | |
| Id = Guid.NewGuid(); | |
| Name = name; | |
| Email = email; | |
| Validate(this, new CustomerValidator()); | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| public class CustomerValidator : AbstractValidator<Customer> | |
| { | |
| public CustomerValidator() | |
| { | |
| RuleFor(a => a.Email) | |
| .NotEmpty() | |
| .EmailAddress() | |
| .WithMessage("Invalid email"); | |
| RuleFor(a => a.Name) | |
| .NotEmpty() | |
| .WithMessage("Name cannot be empty"); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment