jQuery validate - require_from_group重复错误消息

时间:2014-01-24 21:40:09

标签: javascript jquery jquery-validate

我有一个表单,它有三对开始/结束日期。对于每一对我验证两个输入是否已填写或者没有填写,因为它不允许填写开始日期而不是结束日期,反之亦然,加上,我不能发送表格没有至少有一对填写完毕。

每对的验证工作正常,但是规则应该验证三对中的至少一对是否填写在表单的第一个和最后一个字段中重复错误消息。

我写了一个fiddle来举例解释这个问题。我只想显示一条消息,而不是两条消息,因为它正在发生。我做错了什么?

其他疑问,我可以使用require_from_group来验证该对,而不是验证六个输入中的每一个吗?

编辑StackOverFlow,如果强迫我放一些代码,因为我提供了一个小提琴。你可以忽略它,因为它已经在小提琴中了。

HTML:

<div id="msgErros" class="mensagens_erro"></div>
<form>
    <table width="95%" id="tabela_interna">
        <thead><tr valign="middle"><th colspan="6">Report</th></tr></thead>
            <tbody>
                <tr valign="middle">
                    <td width="14%" align="left" class="td_label"><label for="dataInicialSolicitacao">Data de Solicita&ccedil;&atilde;o Inicial</label></td>
                    <td width="25%" align="left" class="td_dados">
                        <input type="text" name="filtro.dataInicialSolicitacao" size="12" value="" id="dataInicialSolicitacao" class="data atLeastOneRequired"/>
                    </td>
                    <td width="12%" align="left" class="td_label"><label for="dataFinalSolicitacao">Data de Solicita&ccedil;&atilde;o Final</label></td>
                    <td width="25%" align="left" class="td_dados">
                        <input type="text" name="filtro.dataFinalSolicitacao" size="12" value="" id="dataFinalSolicitacao" class="data atLeastOneRequired"/>
                    </td>
                </tr>
                <tr valign="middle">
                    <td width="14%" align="left" class="td_label"><label for="dataInicialLiberacao">Data de Libera&ccedil;&atilde;o Inicial</label></td>
                    <td width="25%" align="left" class="td_dados">
                        <input type="text" name="filtro.dataInicialLiberacao" size="12" value="" id="dataInicialLiberacao" class="data atLeastOneRequired"/>
                    </td>
                    <td width="12%" align="left" class="td_label"><label for="dataFinalLiberacao">Data de Libera&ccedil;&atilde;o Final</label></td>
                    <td width="25%" align="left" class="td_dados">
                        <input type="text" name="filtro.dataFinalLiberacao" size="12" value="" id="dataFinalLiberacao" class="data atLeastOneRequired"/>
                    </td>
                </tr>
                <tr valign="middle">
                    <td width="14%" align="left" class="td_label"><label for="dataInicialInternacao">Data de Interna&ccedil;&atilde;o Inicial</label></td>
                    <td width="25%" align="left" class="td_dados">
                        <input type="text" name="filtro.dataInicialInternacao" size="12" value="" id="dataInicialInternacao" class="data atLeastOneRequired"/>
                    </td>
                    <td width="12%" align="left" class="td_label"><label for="dataFinalInternacao">Data de Interna&ccedil;&atilde;o Final</label></td>
                    <td width="25%" align="left" class="td_dados">
                        <input type="text" name="filtro.dataFinalInternacao" size="12" value="" id="dataFinalInternacao" class="data atLeastOneRequired"/>
                    </td>
                </tr>
        </tbody>
    </table>
    <br />
    <div style="width: 95%; text-align: center">
        <button class="margem_botoes" id="gerarRelatorio">Consultar</button>
        <button class="margem_botoes" type="reset">Limpar</button>
    </div>
</form>

JS:

String.prototype.contains = function(sub) { return this.indexOf(sub) != -1; };

$("form").validate({
    rules: {
        "filtro.dataInicialSolicitacao": { require_from_group: [1, ".atLeastOneRequired"], ifDateIsFilledOtherOneIsMandatory: "#dataFinalSolicitacao", maximunDifferenceBetweenDates: ["#dataFinalSolicitacao", 90] },
        "filtro.dataFinalSolicitacao": { require_from_group: [1, ".atLeastOneRequired"], ifDateIsFilledOtherOneIsMandatory: "#dataInicialSolicitacao", maximunDifferenceBetweenDates: ["#dataInicialSolicitacao", 90] },
        "filtro.dataInicialInternacao": { require_from_group: [1, ".atLeastOneRequired"], ifDateIsFilledOtherOneIsMandatory: "#dataFinalInternacao", maximunDifferenceBetweenDates: ["#dataFinalInternacao", 90] },
        "filtro.dataFinalInternacao": { require_from_group: [1, ".atLeastOneRequired"], ifDateIsFilledOtherOneIsMandatory: "#dataInicialInternacao", maximunDifferenceBetweenDates: ["#dataInicialInternacao", 90] },
        "filtro.dataInicialLiberacao": { require_from_group: [1, ".atLeastOneRequired"], ifDateIsFilledOtherOneIsMandatory: "#dataFinalLiberacao", maximunDifferenceBetweenDates: ["#dataFinalLiberacao", 90] },
        "filtro.dataFinalLiberacao": { require_from_group: [1, ".atLeastOneRequired"], ifDateIsFilledOtherOneIsMandatory: "#dataInicialLiberacao", maximunDifferenceBetweenDates: ["#dataInicialLiberacao", 90] }
    },
    messages: {
        "filtro.codigoProcedimento": { range: "Por favor, insira um valor entre 1 e 9223372036854775807 ao preencher o cartão." },
        "filtro.codigoHospital": { range: "Por favor, insira um valor entre 1 e 9223372036854775807 ao preencher o estipulante." },
        "filtro.codigoSegurado": { range: "Por favor, insira um valor entre 1 e 9223372036854775807 ao preencher a solicitação." },
        "filtro.numeroSolicitacao": { range: "Por favor, insira um valor entre 1 e 2147483647 ao preencher o referenciado." }
    },
    groups: {
        datasSolicitacao: "#dataInicialSolicitacao #dataFinalSolicitacao",
        datasLiberacao: "#dataInicialLiberacao #dataFinalLiberacao",
        datasInternacao: "#dataInicialInternacao #dataFinalInternacao"
    },
    onfocusout: function (element, event) {
        if (!$(element).attr("class").contains("data")) {
            $.validator.defaults.onfocusout.call(this, element, event);
        }
    }
});

$.extend($.validator.messages, {
    require_from_group: $.format("Por favor, preencha ao menos {0} uma das duplas de datas para realizar a consulta.")
});

$.validator.setDefaults({
    errorContainer : "#msgErros ul",
    errorLabelContainer: "#msgErros",
    wrapper: "li"
});

$.validator.addMethod("trim", function(value, element) {
    return value.length > 0 ? $.trim(value).length > 0 : true;
}, "Por favor, entre com valores diferentes de apenas espaços para o campo.");

$.validator.addMethod("ifDateIsFilledOtherOneIsMandatory", function(value, element, param) {
    var target = $(param);
    if (this.settings.onfocusout) {
        target.unbind(".validate-ifDateIsFilledOtherOneIsMandatory").bind("blur.validate-ifDateIsFilledOtherOneIsMandatory", function() { $(element).valid(); });
    }

    return !(!isDateEmptyOrFilledWithMask(target.val()) && isDateEmptyOrFilledWithMask(value));
},"Por favor, forne&ccedil;a a outra data deste par final e inicial de datas.");

$.validator.addMethod("maximunDifferenceBetweenDates", function(value, element, param) {
    var startDate;
    var endDate;
    if (param[0].contains("Final")) {
        startDate = value;
        endDate = $(param[0]).val();
    } else {
        startDate = $(param[0]).val();
        endDate = value;
    }

    return areBothDatesFilled(startDate, endDate) ? (($.datepicker.parseDate("dd/mm/yy", endDate) - $.datepicker.parseDate("dd/mm/yy", startDate)) / 86400000) <= param[1] : true;
}, $.validator.format("Por favor, forneça uma diferen&ccedil;a de no m&aacute;ximo {1} dias entre as datas."));

function areBothDatesFilled(firstDate, secondDate) {
    return !isDateEmptyOrFilledWithMask(firstDate) && !isDateEmptyOrFilledWithMask(secondDate);
}

function isDateEmptyOrFilledWithMask(date) {
    return date == "" || date == "__/__/____";
}

$(".data").mask("99/99/9999").numeric().datepicker().attr("maxlength", 10);

$("form").on("reset", function(event) {
    event.preventDefault();
    $(this).clearForm();
    $("#respostaRelatorio").jqGrid("GridUnload");
    $(".erasableInfo").empty();
    $("#msgErros").empty();
});

1 个答案:

答案 0 :(得分:3)

groups选项通常与require_from_group方法结合使用。它将所有错误消息组合成一个指定字段。然后,您可以使用CSS和/或errorPlacement选项根据自己的喜好定位消息。

groups: {
    someArbitraryName: "fieldName1 fieldName2 fieldName3"
}

请参阅文档:http://jqueryvalidation.org/validate