Validate data from an object with DataAnnotations C # Winforms

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 in the database:

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 would like to validate the post object by DataAnnotations rules and if there were any errors it throws an exception, how can I do this?

    
asked by anonymous 29.10.2016 / 16:58

1 answer

2

Implement a class that is responsible for checking that 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:

In 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 model is valid, the next execution would be Inserir , and if you have any problems, enter try catch with problems with model . I do not know if throwing an exception like this would be appropriate, but if you do not want exception errors to appear, but Error Messages ( MessageBox ) the class can be worked like this:

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");
    }          

} 
  

Thislinkhasanonlineexamplerunningin Console Application only for demonstration, this code has been tested and works as asked in Windows Forms .

References:

30.10.2016 / 01:42