Require input text input with jQuery validator

1

I am making a registration form, and I have three fields to enter values.

I want to make it mandatory to fill in at least one of the three input text.

Does anyone know how to do this with jQuery Validator?

<input type="text" name="produto_preco_p" id="produto_preco_p" class="form-control" value="<?= $produto_preco_p; ?>" placeholder="Preço tamanho P">

<input type="text" name="produto_preco_m" id="produto_preco_m" class="form-control" value="<?= $produto_preco_m; ?>" placeholder="Preço tamanho M">

<input type="text" name="produto_preco_g" id="produto_preco_g" class="form-control" value="<?= $produto_preco_g; ?>" placeholder="Preço tamanho G">
    
asked by anonymous 27.01.2016 / 00:31

2 answers

2

In order for at least one of the three to be mandatory, I suggest creating a rule that takes a selector (a class for example) common among the other fields for validation, after which you can scan and check if any of the fields have value .

Html:

<input type='text' class="toValidate" requiredBased=".toValidate" />
<input type='text' class="toValidate" requiredBased=".toValidate" />
<input type='text' class="toValidate" requiredBased=".toValidate" />

JavaScript:

//Crio a regra
$.validator.addMethod("requiredBased", function(value, element, param) {
  //passo pelo seletor verificando se todos tem val()
  return (($(param).filter(function() {
    return $(this).val();
  }).length > 0) ? true : false);
}, "");

Follow jsfiddle .

    
27.01.2016 / 11:13
1

The "easy" one would be to use the required of HTML5, but it will make all fields mandatory.

<input type="text" name="produto_preco_p" id="produto_preco_p" class="form-control" value="<?= $produto_preco_p; ?>" placeholder="Preço tamanho P" required>

If your application allows, it forces all fields to be filled in and then handles at the time of insertion. (For example: It does not have the price of the size G, it guides the user to 0 in the field and then see what it will do, if it inserts 0 in the bank or it turns into null.)

    
27.01.2016 / 11:06