Skip to content

Instantly share code, notes, and snippets.

@danielplawgo
Created June 14, 2018 11:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danielplawgo/896884c266a39cfb17e275fe0bda30d7 to your computer and use it in GitHub Desktop.
Save danielplawgo/896884c266a39cfb17e275fe0bda30d7 to your computer and use it in GitHub Desktop.
Fluent Validation
static void Main(string[] args)
{
var user = new User()
{
CreateInvoice = true,
Nip = "123",
Email = "daniel@plawgo.pl",
Orders = new List<Order>()
{
new Order(){Product = "Laptop"},
new Order(){Cost = 14}
}
}
;
var validator = new UserValidator(new UserLogic());
var validationResult = validator.Validate(user);
if (validationResult.IsValid == false)
{
foreach (var error in validationResult.Errors)
{
Console.WriteLine("{0}: {1}", error.PropertyName, error.ErrorMessage);
}
}
}
public class User
{
public User()
{
Address = new Address();
}
[Display(Name = "Nazwa użytkownika")]
public string Name { get; set; }
public string Email { get; set; }
public bool CreateInvoice { get; set; }
public string Nip { get; set; }
public Address Address { get; set; }
public List<Order> Orders { get; set; }
}
public class UserValidator : AbstractValidator<User>
{
public UserValidator(IUserLogic userLogic)
{
RuleFor(u => u.Name)
.NotEmpty();
RuleFor(u => u.Email)
.NotEmpty()
.WithMessage(UserResources.EmailIsRequiredError);
RuleFor(u => u.Email)
.EmailAddress()
.WithMessage("Email ma niepoprawny format");
When(u => u.CreateInvoice, () =>
{
RuleFor(u => u.Nip)
.Cascade(CascadeMode.StopOnFirstFailure)
.NotEmpty()
.WithMessage("Nip jest wymagany")
.Must(nip => IsNipValid(nip))
.WithMessage("Nip ma niepoprawny format") ;
});
RuleFor(u => u.Email)
.Must(email => userLogic.Exist(email))
.WithMessage(u => string.Format("Użytkownik o adresie {0} już istnieje.", u.Email));
RuleFor(u => u.Address)
.SetValidator(new AddressValidator());
RuleFor(u => u.Orders)
.SetCollectionValidator(new OrderValidator());
}
private bool IsNipValid(string nip)
{
if (nip == null)
{
return false;
}
if (nip.Length != 10)
{
return false;
}
return true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment