-
Notifications
You must be signed in to change notification settings - Fork 2
/
PersonValidator.cs
55 lines (40 loc) · 1.69 KB
/
PersonValidator.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
using FluentValidation;
using Microsoft.Extensions.Configuration;
using ValidationSample.BusinessLayer.Resources;
using ValidationSample.Shared.Models;
namespace ValidationSample.BusinessLayer.Validations;
public class PersonValidator : AbstractValidator<Person>
{
public PersonValidator(IConfiguration configuration)
{
//ClassLevelCascadeMode = CascadeMode.Stop;
RuleFor(p => p.FirstName).NotEmpty().WithMessage(Messages.FieldRequried)
.MaximumLength(30)
.WithName(Messages.FirstName);
RuleFor(p => p.LastName).NotEmpty().WithMessage(Messages.FieldRequried)
.MaximumLength(50)
.WithName(Messages.LastName);
RuleFor(p => p.BirthDate).LessThan(DateTime.UtcNow);
RuleFor(p => p.Country).Length(2);
RuleFor(p => p.Discount).NotEmpty().GreaterThan(0).When(p => p.HasDiscount);
RuleFor(p => p.FiscalCode).Must(BeAValidFiscalCode).When(p => p.Country == "IT");
RuleFor(p => p.Categories).NotEmpty().Must(MustBeUnique);
RuleForEach(p => p.Categories).ChildRules(category =>
{
category.RuleFor(p => p.ProductsIds).NotEmpty();
});
RuleFor(p => p).Must((p, _) => BeAValidPerson(p));
RuleFor(p => p.Type).IsInEnum();
}
private static bool BeAValidPerson(Person person)
=> true;
private static bool MustBeUnique(IEnumerable<FavoriteCategory> categories)
{
var duplicates = categories.GroupBy(c => c.CategoryId)
.Where(g => g.Count() > 1)
.Select(k => k.Key);
return !duplicates.Any();
}
private static bool BeAValidFiscalCode(string fiscalCode)
=> fiscalCode?.Length == 16;
}