Last active
April 15, 2024 03:53
-
-
Save YurePereira/2d347883a5b0d3dadce31be32c89477b to your computer and use it in GitHub Desktop.
Sabia que podemos validar dados dentro de nossas classes no C# usando uma biblioteca muito flexível e simples de usar chamada FluentValidation, olhem um exemplo de sua utilização.
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
using System; | |
using FluentValidation; | |
using FluentValidation.Results; | |
public class Program | |
{ | |
public static void Main() | |
{ | |
var dataNascimento = DateOnly.Parse("04/15/1890"); | |
var novaPessoa = new Pessoa { | |
Id = 1, | |
Nome = "Yure Pereira", | |
DataNascimento = dataNascimento, | |
CPF = "99922244499_" | |
}; | |
PessoaValidator validator = new PessoaValidator(); | |
ValidationResult results = validator.Validate(novaPessoa); | |
if(!results.IsValid) | |
{ | |
foreach(var failure in results.Errors) | |
{ | |
Console.WriteLine("Campo: " + failure.PropertyName | |
+ ". Erro encontrado: " + failure.ErrorMessage); | |
} | |
} else { | |
Console.WriteLine("Dados estão todos corretos!"); | |
} | |
} | |
} | |
public class Pessoa | |
{ | |
public int Id { get; set; } | |
public string Nome { get; set; } | |
public DateOnly DataNascimento { get; set; } | |
public string CPF { get; set; } | |
} | |
public class PessoaValidator : AbstractValidator<Pessoa> | |
{ | |
public PessoaValidator() | |
{ | |
RuleFor(x => x.Nome) | |
.NotEmpty() | |
.WithMessage("O campo nome é obrigatório"); | |
RuleFor(x => x.DataNascimento) | |
.NotEmpty() | |
.WithMessage("O campo data é obrigatório"); | |
RuleFor(x => x.CPF) | |
.MaximumLength(11) | |
.WithMessage("O campo CPF deve conter 11 caracteres"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment