I have three fields, two inputs text
and between them a select
. If one of the first two is filled in the other becomes mandatory. The problem is that when a single value, in the case the last option, of the select is filled all three become mandatory.
Is it possible to have dynamic rules with this plugin, ie when checking the value of select make the third field mandatory?
HTML
<div id="msgErros"></div>
<form>
<label for="tempoInicial">Tempo Inicial</label>
<input type="text" name="filtro.tempoInicial" size="8" value="" id="tempoInicial" class="tempo" />
<br />
<label for="operadorTempo">Operador de Tempo</label>
<select name="filtro.valorOperadorTempo" id="operadorTempo" class="tempo">
<option value="">-- Selecione --</option>
<option value="1">> - Maior</option>
<option value="2">< - Menor</option>
<option value="3">Entre</option>
</select>
<br />
<label for="tempoFinal">Tempo Final</label>
<input type="text" name="filtro.tempoFinal" size="8" value="" id="tempoFinal" />
<br />
<button>Enviar</button>
</form>
JavaScript
$.validator.addMethod("skip_or_fill_minimum", function (value, element, options) {
var $fields = $(options[1], element.form),
$fieldsFirst = $fields.eq(0),
validator = $fieldsFirst.data("valid_skip") ? $fieldsFirst.data("valid_skip") : $.extend({}, this),
numberFilled = $fields.filter(function () {
return validator.elementValue(this);
}).length,
isValid = numberFilled === 0 || numberFilled >= options[0];
// Store the cloned validator for future validation
$fieldsFirst.data("valid_skip", validator);
// If element isn't being validated, run each skip_or_fill_minimum field's validation rules
if (!$(element).data("being_validated")) {
$fields.data("being_validated", true);
$fields.each(function () {
validator.element(this);
});
$fields.data("being_validated", false);
}
return isValid;
}, jQuery.validator.format("Please either skip these fields or fill at least {0} of them."));
$("form").validate({
errorContainer: "#msgErros ul",
errorLabelContainer: "#msgErros",
wrapper: "li",
rules: {
"filtro.tempoInicial": {
skip_or_fill_minimum: [2, ".tempo"]
},
"filtro.valorOperadorTempo": {
skip_or_fill_minimum: [2, ".tempo"]
}
},
groups: {
tempos: "filtro.tempoInicial filtro.valorOperadorTempo"
},
onfocusout: function (element, event) {
var classeCSSElemento = $(element).attr("class");
var classeCSSElementoIndefinida = typeof classeCSSElemento === "undefined";
if (classeCSSElementoIndefinida || (!classeCSSElementoIndefinida && !classeCSSElemento.contains("tempo"))) {
$.validator.defaults.onfocusout.call(this, element, event);
}
}
});