Obligate fields from selected radio

4

How do I jquery validate validate only the fields of the selected radio input?

Example:

I have 2 input radio (individual and corporate) I want to validate only the selected radio fields.

If the user selects a physical person, he / she will only validate the fields of physical person and the same with the legal entity.

    
asked by anonymous 15.09.2015 / 05:28

2 answers

1

The .rules() method of jQuery Validation accepts any selector, you can add class or attribute role to your inputs and from deletes to remove / remove the validations from the val of your radiobox as in the example below.

HTML:

<form>
    <input type="radio" value="fisica">Física
    <input type="radio" value="juridica">Jurídica
</form>

JavaScript:

function setPessoaFisicaValidation() {

    /*antes de setar validação de pessoa física removo da jurídica*/
    $('.juridica').rules("remove", "required");

    /*seta validação da pessoa física*/
    $('.fisica').rules("add", {
        required: true
    });
}

function setPessoaJuridicaValidation() {
    /*faz o mesmo da fisica só que inverso >D*/
    $('.fisica').rules("remove", "required");

    /*seta validação da pessoa juridica*/
    $('.juridica').rules("add", {
        required: true
    });
}

$(document).ready(function () {

    /*você pode pegar o evento de change do seu radio*/
    $('input[type="radio"]').change(function () {
        /*e a partir da opção chama o método para setar a regra de validação :D*/
        if ($(this).val() == 'fisica')
            setPessoaFisicaValidation();
        else
            setPessoaJuridicaValidation();
    });
});
    
15.09.2015 / 14:35
0

I think it could be done like this:

$(function(){
        $('input[name=type_doc]').change(function(){
          $("input.form").attr('disabled', true).removeClass('required').removeAttr('required');
          $("input."+$(this).val()).addClass('required').attr('required',true).removeAttr('disabled');
        })
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><html><body><label><inputtype="radio" name="type_doc" value="pf" /> CPF</label>
    <label><input type="radio" name="type_doc" value="pj" /> CNPJ</label>
    <br>
    CPF: <input type="text" name="cpf" value=""  class="form pf" disabled/>
    Nome: <input type="text" name="nome_completo" value=""  class="form pf" disabled/>
    <br>
    CNPJ: <input type="text" name="cnpj" value=""  class="form pj" disabled/>
    Razão Social: <input type="text" name="razao_social" value=""  class="form pj" disabled/>
    
    
  </body>
</html>
    
15.09.2015 / 05:51