Validate data from an object with Dataannotations C# Winforms

Asked

Viewed 391 times

3

Good afternoon, I have the following Entity class marked by Data Annotations:

public class Cargo
{
    [Key]
    [Display(Name ="Código")]
    public int Codigo { get; set; }

    [Required(AllowEmptyStrings =false, ErrorMessage = "A descrição do cargo é obrigatória")]
    [Display(Name = "Descrição")]
    public string Descricao { get; set; }

    [Display(Name = "Ativo")]
    public bool Ativo { get; set; }

}

I have the following method that captures class errors:

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

Finally I have the following method that validates the Insert at the bank:

public void ValidarInsercao(Cargo cargo)
    {

        if (string.IsNullOrWhiteSpace(cargo.Descricao))
        {
            throw new ArgumentNullException("A descrição do cargo não tem um valor válido.");
        }

        objCargo.Inserir(cargo);//tenta inserir no banco de dados

    }

I’d like to validate the object office by the rules of Dataannotations and if there were any mistakes he’d make an exception, how can I do that?

1 answer

2


Implement a class that is responsible for checking your Model is valid:

public sealed class ModelValid
{                                 
    public ICollection<ValidationResult> ValidationResults { get; private set; }
    public bool IsValid { get; private set; }
    public ModelValid(object model)            
    {
        ValidationResults = new List<ValidationResult>();
        IsValid = Validator.TryValidateObject(model, 
            new ValidationContext(model), 
            ValidationResults, true);            
    }
    public ModelValid(object model, bool throwIfExists)
        :this(model)
    {
        if (throwIfExists) ThrowException();
    }
    public void ThrowException()
    {               
        throw new ValidationException(ErrorMessages());
    }  
    public string ErrorMessages()
    {
        string message = string.Empty;
        if (!IsValid)
        {
            if (ValidationResults != null &&
                ValidationResults.Count > 0)
            {                              
                IEnumerator<ValidationResult> results =
                    ValidationResults.GetEnumerator();
                while (results.MoveNext())
                {
                    ValidationResult vr = results.Current;
                    message += vr.ErrorMessage + System.Environment.NewLine;
                }                    
            }
        }
        return message;
    }
}

How to use:

At the event Click of a Button:

private void button1_Click(object sender, EventArgs e)
{
    try
    {
        Cargo cargo = new Cargo { };
        ModelValid modelValid = new ModelValid(cargo, true);
        objCargo.Inserir(cargo);            
    }
    catch (Exception ex)
    { 
        throw ex;
    }
}

If the model is valid, the next execution would be Inserir, and if you have any problems get into action try catch with the problems of model. I don’t know if making an exception like that would be appropriate, but if you don’t want any exceptions to appear, but, Error Messages (MessageBox) class can be worked as follows:

private void button1_Click(object sender, EventArgs e)
{   

    Cargo cargo = new Cargo { };

    ModelValid modelValid = new ModelValid(cargo);
    if (modelValid.IsValid)
    {
        objCargo.Inserir(cargo);
    }
    else
    {
        MessageBox.Show(modelValid.ErrorMessages(), "Error");
    }          

} 

inserir a descrição da imagem aqui

This link has an online example running on Console Application for demonstration only, being that this code has been tested and works as asked in Windows Forms.

References:

  • I will try to implement here friend as soon as I can mark as resolved!

  • 1

    Friend your class worked perfectly and could not be better, thank you very much!

Browser other questions tagged

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