This package provide a simple way to validate class and entities of your project
License
—
Deps
0
Install Size
—
Vulns
✓ 0
Published
Mar 27, 2022
$ dotnet add package SimpleEntityValidation public class Client {
public Guid Id { get; set; }
public string Name { get; set; }
public string Document { get; set; }
public string Email { get; set; }
public DateTime CreationDate { get; set; }
public int YearsOld { get; set; }
public string Password { get; set; }
public string CheckPassword { get; set; }
public List<string> Tags { get; set; }
}
public class ClientValidator : AbstractValidator<Client>
{
public ClientValidator()
{
RuleFor(x => x.Name).NotNull().MinLength(5);
RuleFor(x => x.Password).NotNull().MustBeEqual(x => x.CheckPassword);
RuleFor(x => x.Email).NotNull().MinLength(10);
RuleFor(x => x.Document).MaxLength(11);
RuleFor(x => x.Password).NotEqual("12345");
RuleFor(x => x.YearsOld).GreaterThan(17);
RuleFor(x => x.Tags).NotNull();
RuleFor(x => x.YearsOld)
.LessThan(150)
.WithMessage("The field 'YearsOld' is not less than '150'");
}
}
class Program
{
protected Program() { }
static void Main(string[] args)
{
Client client = new() { Password = "12345", CheckPassword = "12312s1", YearsOld = 155 };
ClientValidator clientValidator = new();
ValidationResult result = clientValidator.Validate(client);
if (result.ValidationFailures.Count > 0)
Console.WriteLine("Client entity validation with errors:");
result.ValidationFailures.ToList().ForEach(failure => Console.WriteLine($"{failure.Message}"));
Console.ReadKey();
}
}
public class ClientValidator : AbstractValidator<Client>
{
public ClientValidator()
{
RuleFor(x => x.Name).NotNull().MinLength(5);
RuleFor(x => x.Password).NotNull().MustBeEqual(x => x.CheckPassword);
RuleFor(x => x.Email).NotNull().MinLength(10);
RuleFor(x => x.Document).MaxLength(11);
RuleFor(x => x.CreationDate).NotNull();
RuleFor(x => x.Tags).NotNull();
RuleFor(x => x.Nums).NotNull();
RuleFor(x => x.Password).NotEqual("12345");
RuleFor(x => x.YearsOld).GreaterThan(17);
RuleFor(x => x.Address).SetBaseValidator(new AddressValidator()); // Complex validation
RuleFor(x => x.YearsOld)
.LessThan(150)
.WithMessage("The field 'YearsOld' is not less than '150'");
}
}
public class AddressValidator : AbstractValidator<Address>
{
public AddressValidator()
{
RuleFor(x => x.Street).NotNull().MaxLength(150);
RuleFor(x => x.City).NotNull().MaxLength(100);
RuleFor(x => x.Country).NotNull().MinLength(2);
}
}