Force fields from selected radio

Asked

Viewed 707 times

4

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

Example:

I have 2 input radio (natural person and legal person) I want to validate only the selected radio fields.

If the user selects natural person will validate only the physical person fields and the same happens to the legal person.

2 answers

1


The method .rules() jQuery Validation accepts any selector, you can add class or attribute role in your inputs and from Switch to/remove 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();
    });
});

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><input type="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>

Browser other questions tagged

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