SubModel Conditional Validation MVC 4 C #

2

I have the following problem (I will simplify the classes to facilitate understanding):

public class Class1 {
    [Required]
    public int? Id_Estabelecimento { get; set; }
    public string Nm_Nome { get; set; }
}

public class Class2 {
    [Required]
    public int Id_Classe2 { get; set; }
    public int Tipo_Cadastro { get; set; }
    public Classe1 CLASSE1 { get; set; }
}

The problem is as follows: If Class_Type is 1, CLASS1 (and its attributes) should not be Required, otherwise Class 2 should be validated normally.

OBS1: I can do this procedure on Controller (using ModelState Clear), but I wanted to do it on the Client Side with unobtrusive jquery.

OBS2: I know it involves conditional validation. I have already done a conditional validation involving two attributes of the same class. In this case I'm trying to "hack" the data annotations of another class.

Has anyone ever been through something like this? Or am I complicating things?

    
asked by anonymous 26.08.2014 / 23:02

1 answer

1

It's complicated, yes. Never validation may be different because of client change.

In fact, clearing ModelState is bad practice in almost all cases.

Implement your Class2 as follows:

public class Class2 : IValidatableObject
{
    [Key]
    public int Class2Id { get; set; }
    [Required]
    public int TipoCadastro { get; set; }

    public virtual Classe1 Classe1 { get; set; }

    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) 
    { 
        if (TipoCadastro == 1) { 
            // Coloque a validação aqui. Dando erro, retorne um ValidationResult.
            yield return new ValidationResult("Campos tal e tal são obrigatórios.");
        }
    }
}

To indicate a particular field, add a array of String s to the end, indicating which fields the message covers:

yield return new ValidationResult("Campo Nome é obrigatório.", new string[] { "Nome" });
    
26.08.2014 / 23:07