What is the best validation strategy before data persists?

Asked

Viewed 362 times

5

I’m used to . NET using C# and Entityframework.

And there in the Entity we have the dataanotations. When I create the entity in C#, for example person, just put the datanotaations and the Entity validates for me:

public partial class Tab_Parente
{
  [Key]
  public int Cpf { get; set; }

  [Display(Name = "Nome da Pessoa")]
  [Required(ErrorMessage = "O Nome Aluno deve ser informado.")]
  publicint Nome{ get; set; }

  [Display(Name = "CPF")]
  [StringLength(15, ErrorMessage = "O CPF deve ter no máximo 15 caracteres.")]
  public string Cpf { get; set; }
}

But I started in a project that requires ADO. Then came the question: What is the best way to validate the data before persisting with ADO?

Will I have to create a validation method for each field and call all of them before sending a command update or insert to the bank?

Like see if the ID already exists with a select. See if the reported CPF has more than 15 characters, etc., all in hand?

--------------------EDITION--------------------- I found my answer:

Good contrary to what I previously thought and stated Dataannotations can rather be used in Windowsforms applications.

Many people do not know but Data Annotations are not exclusive to MVC, nor much less restricted to the Entity Framework. Following a tutorial from Macoratti on the use of: Validator.Tryvalidateobject(obj, context, resultValidacao , true) I was able to build a class getValidationErros(Object obj), which returns us a list of errors of an entity. In my Windows Forms project and using pure ADO.

Look how it turned out:

Entity

public class HoldingGrupoEnt : GeralEntidade, IHoldingGrupoEnt
{
    [Display(Name = "Código Grupo", Description = "Código do grupo.")]
    [Required(ErrorMessage = "000001 - Código Grupo não pode ficar vazio em Holding Grupo.")]
    [RegularExpression(@"^[0-9]*$", ErrorMessage = "000002 - Somente números (de 0 a 9) são permitidos para Código Grupo em Holding Grupo.")]
    public string CodigoGrupo { get; set; }

    [Display(Name = "Nome Fantasia", Description = "Nome completo.")]
    [Required(ErrorMessage = "O nome fantasia é obrigatório.")]
    public string NomeFantasia { get; set; }

    public IHoldingGrupoStatusRegistroEnt HoldingGrupoStatusRegistroEnt { get; set; }

    public DateTime? DataCadastro { get; set; }
}

Class Validation

public static class Validacao
{
    public static IEnumerable<ValidationResult> getValidationErros(object obj)
    {
        var resultadoValidacao = new List<ValidationResult>();
        var contexto = new ValidationContext(obj, null, null);
        Validator.TryValidateObject(obj, contexto, resultadoValidacao, true);
        return resultadoValidacao;
    }
}

Entity Context Method (where Update, Insert, etc are)

public override bool ValidaRegistro()
{
    DadosValidados = false;

    if (DadosRecebidos)
    {
        var erros = Validacao.getValidationErros(ObjetoEnt);
        foreach (var error in erros)
        {
            MessageBox.Show((error.ErrorMessage));
        }
    }
    //return DadosValidados = (erros.ToString() = 0) ;
    return DadosValidados = true;
}

Besides I don’t know how yet but I’ve been told that Fluent Validation can also be used outside the MVC world.

  • 1

    https://github.com/JeremySkinner/FluentValidation would use this

  • Oops! So there’s still hope, rsrs. I’ll take a look @Marconcilio

1 answer

7

That’s basically it. Of course it doesn’t necessarily have to be a method for each validation, it can be a method that does it all. This is a question of project organization. Each project may require a different solution.

Or you can create a framework similar to EF to automate this and have similar behavior where you can only annotate and use. The annotations even exist, but there is nothing to perform the necessary actions when they find these annotations. Surely there are some ready ones who can already do such a task.

  • Hummm pouxa life. Then I’ll have a nice job ahead of me, rsrs. Better get started soon. Thanks for the reply.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.