Skip to content

Instantly share code, notes, and snippets.

@wellingtonjhn
Last active November 25, 2018 22:00
Show Gist options
  • Select an option

  • Save wellingtonjhn/bd7d786b975b09b0e258607f1b0f50f5 to your computer and use it in GitHub Desktop.

Select an option

Save wellingtonjhn/bd7d786b975b09b0e258607f1b0f50f5 to your computer and use it in GitHub Desktop.
Entity with Validator Sample
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;
}
}
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());
}
}
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