Hide field required and not required

0

I have a form. In this form I have two radiobutton with two options.

1) Questao 1 (Obrigatorio)
1 = Sim 
2 = Nao 

______________________

2) Questao 2(Obrigatorio)
1 = Vivo
2 = Morto

If this question 1 is = Yes Question 2 loses the obligatoriness, it will not be an obligatory question to be answered, but if it is = No, question 2 will return with the obligation.

Does anyone have a way to help me with this?

Thank you in advance.

    
asked by anonymous 14.02.2017 / 19:12

3 answers

5

Good afternoon guys, I've done the following validation

var value = $('input[name="CAMPO1"]').val();

if (value == '1') {
    $('[name="CAMPO2"]').rules('remove', 'required');
} else {
    $('[name="CAMPO2"]').rules('add', 'required');
}

and it worked perfectly. Thanks for the help!

    
14.02.2017 / 20:24
1

If you are using client validation in javascript, you can add the data-val-required attribute and remove it when you do not want the field to be mandatory, something like this:

// Obrigatório
$(campo).attr("data-val-required", "*");

// Não obrigatório
$(campo).removeAttr("data-val-required");

It may be necessary to tell form to parse the controls again, which you can do using this command:

$.validator
        .unobtrusive
        .parse("form");
    
14.02.2017 / 19:35
0

In this case you would need to create a validator , implementing IValidatable and IClientValidatable . One suggestion would be to create something equal [Required] , but only if another property or condition were true.

    
14.02.2017 / 19:22