Require input text filling with jQuery Validator

Asked

Viewed 458 times

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">

  • Why don’t you use a radio for the user to choose which size and leave only an input text to pick up the value ?

2 answers

2


In order to be mandatory at least one of the three, I suggest creating a rule that takes as parameter a selector (a class for example) common among the other fields for validation, after that 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);
}, "");

Follows jsfiddle.

  • 1

    Perfect, Brunno! That’s what it was. I was going to ask how to put error message in the validation, but I saw that just insert the text between the quotes at the end. Thanks for saying!

1

The most "easy" would be to use the required 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, you must fill in all the fields and then deal with them at the time of insertion. (For example: It has no price of size G, it guides the user to put 0 in the field and then see what he will do, if he inserts 0 in the bank or turns null).

Browser other questions tagged

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