Client-Side Validation (Jquery) conditional attribute

2

Late!

I am performing a complex validation on a specific class with the following code (reduced for simplicity):

public class Classe1 : IValidatableObject 
{
    [Key]
    public int Id_Classe1 { get; set; }
    [Required]
    public int Id_Estado { get; set; }
    public virtual Classe2 CLASSE2 { get; set; }

    public Classe1() {
    CLASSE2 = new Classe2();
}

public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) {
    if (this.Id_Estado == 1) 
    {
        if (CLASSE2.Nm_Classe2 == null)
            yield return new ValidationResult("Campo Nome é obrigatório.", new string[] { "CLASSE2.Nm_Classe2" });
    }
}

In the controller (ModelState.IsValid) the validation is ok. Now I need to reflect this validation on the Client Side, with unobtrusive jquery. Can anyone give me an orientation on how to do?

    
asked by anonymous 29.08.2014 / 18:28

2 answers

1

To whom it may concern, I found what I needed, I resolved as follows:

I created a conditional validator that tests a specific attribute of the class and handles the attribute of the other class, like this:

public class Classe1 : IValidatableObject
{
    [Key]
    public int Id_Classe1 { get; set; }
    [Required]
    public int Id_Estado { get; set; }
    [Required]
    public virtual Classe2 CLASSE2 { get; set; }

    [IgualOuDiferente("Id_Estado", "1", "Igual", ErrorMessage = "Campo requerido")]
    public string Teste
    {
        get { return this.CLASSE2.Nm_Classe2; }
        set { CLASSE2.Nm_Classe2 = value; }
    }
}

That is, if the attribute "Status_ID" is "Equal" to "1", it requires you to enter Nm_Classe2 , even if it is in another class ( Classe2 ) without [Required] .

In View it looks like this:

@Html.TextBoxFor(m => m.Teste)
@Html.ValidationMessageFor(m => m.Teste)

Valew!

    
02.09.2014 / 15:10
0

Implementing custom attributes that implement an interface called IClientValidatable . In this question users show in detail how to do this.

In this case, your Validate event enters as a validation bonus, server-side only.

    
29.08.2014 / 19:49