Conditional Sub-model Validation MVC 4 C#

Asked

Viewed 478 times

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 this: If Type is 1, the CLASSE1 (and its attributes) should not be Required, if 2 is the class should be validated normally.

OBS1: I can do this in Controller (using Modelstate Clear), but I wanted to do it in Client Side with jquery unobtrusive.

OBS2: I know it involves a conditional validation. I have already made a conditional validation involving two attributes of the same class. In this case I am wanting to "invade" the data Annotations of another class.

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

1 answer

1

Is complicating yes. Never validation may be different because of client switching.

In fact, clean up the ModelState is a 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 certain field, add a array of Strings at the end, indicating for which fields the message covers:

yield return new ValidationResult("Campo Nome é obrigatório.", new string[] { "Nome" });
  • I’m not getting validation in the client-side. Using @Html.Validationmessagefor(m => m.Typehost) nothing returns. The field accepts any data and seems to do no validation. It would have something more to do than the above?

  • @Felipe Editei my reply.

  • Thank you for your attention. I still can’t get validation in client-side. Can you clarify if 1 - O public IEnumerable<ValidationResult> goes into Classe2 ? 2 - What goes in place of the //Place the validation here..? 3 - The ValidationMessageFor Is it really Tipocadastro? and 4 - I need some code in js for unobtrusive to work? (I’m looking at several forums that indicate the same as you, but it doesn’t work, I think I’m skipping some steps). Valew, my man!

  • 1 - The public IEnumerable<ValidationResult> goes inside the class that will be validated; 2 - This comment is only to indicate that in that piece you will have to write your validation. I don’t know your business rules; 3 - The ValidationMessageFor is the Helper that generates the object of View suitable to display validation messages; 4 - Has several tutorials on unobstrusive... can be several things missing. I suggest you go opening up more questions.

  • 1

    Valew @Gypsy, after a little time heating the batteries I ended up getting in a trance. The above validation is performed when Modelstate.isValid is working well. Now I need to reflect this in the form, via unobtrusive. As you suggested, I will open another question with this specific theme. [s]

Browser other questions tagged

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