jQuery验证定制方法未针对空字段调用(其他字段也可以)

时间:2019-03-04 15:20:33

标签: javascript jquery jquery-validate

我有一个输入表,其中包括3个生日的日期。

我已经编写了一种自定义验证方法来验证这3个部分,如果输入了3个字段之一,则调用该方法,但是如果所有或任何字段为空,则需要调用它。

我有console.log命令,所以我可以查看该方法是否被调用,如果单击带有空白字段的提交,您会看到它未被调用,请在日期字段之一中输入一个数字,它将被调用。

我可以找到的所有类似问题都是根本没有验证表单的地方,这确实验证了其他字段。

https://jsfiddle.net/zacmarshall/Lrvsachp/8/中有示例代码

html

 <form id="form1"><br/><br/><br/>
        <div id="form_group_puid" class="form-group">
            <span class="label">field1</span>
            <span class="hint"></span>
            <div id="error_location_puid"></div>
            <input class="input !-width-one-quarter" id="puid" name="puid"  required>
        </div>

        <div id="form_group_date_of_birth" class="form-group">
            <fieldset class="fieldset" aria-describedby="date_of_birth_hint" role="group">
                <span class="label">Date of birth</span>
                <span id = "tour_start_date_hint" class="hint">e.g. 31 3 1980</span>

                <div class="date-input" id="date_of_birth">
                <div id="error_location_date_of_birth"></div>
                    <div class="date-input__item">

                        <div class="form-group">
                            <label class="label date-input__label" for="date_of_birth_day">
                                Day
                            </label>
                            <div id="error_location_date_of_birth_day"></div>
                            <input class="input " id="date_of_birth_day" name="date_of_birth_day" type="number" pattern="[0-9]*" min="1" max="31" required>
                        </div>
                    </div>
                    <div class="date-input__item">

                        <div class="form-group">
                            <label class="label date-input__label" for="date_of_birth_month">
                                Month
                            </label>
                            <div id="error_location_date_of_birth_month"></div>
                            <input class="input " id="date_of_birth_month" name="date_of_birth_month" type="number" pattern="[0-9]*" min="1" max="12" required>
                        </div>
                    </div>
                    <div class="date-input__item">

                        <div class="form-group">
                            <label class="label date-input__label" for="date_of_birth_year">
                                Year
                            </label>
                            <div id="error_location_date_of_birth_year"></div>
                            <input class="input" id="date_of_birth_year" name="date_of_birth_year" type="number" pattern="[0-9]*" min="1900" max="2018" required>
                        </div>
                    </div>

                </div>
            </fieldset>

        </div>

        <input type="submit" value="submit" />
    </form>

javascript

$(document).ready(function () {

/* Custom validation method to validate a date based on several fields: */
$.validator.addMethod("datemultiple1", function(value, element, params) {
    console.log("in datemultiple1");
    var daySelector = params[0],
        monthSelector = params[1],
        yearSelector = params[2],
        day = parseInt($(daySelector).val(), 10),
        month = parseInt($(monthSelector).val(), 10),
        year = parseInt($(yearSelector).val(), 10);
        //dateEntered = new Date(year, month - 1, day);
    var dateValid = false;
    //elementDay="#"+daySelector;
    $(daySelector).removeClass("input--error");
    $(monthSelector).removeClass("input--error");
    $(yearSelector).removeClass("input--error");
    console.log(daySelector);
    if (isNaN(day)) {
        console.log("day not numeric");
        $(daySelector).addClass("input--error");
    }
    if (isNaN(month)) {
        console.log("month not numeric");
        $(monthSelector).addClass("input--error");
    }
    if (isNaN(year)) {
        console.log("year not numeric");
        $(yearSelector).addClass("input--error");
    }
    dateEntered = day + "/" + month + "/" + year;
    console.log("in datemultiple" + dateEntered.valueOf());
    if(!isNaN(day) && !isNaN(month) && !isNaN(year)) {
        console.log("all fields entered")
    return this.optional(element) || /^(?:(?:31(\/|-|\.)(?:0?[13578]|1[02]))\1|(?:(?:29|30)(\/|-|\.)(?:0?[1,3-9]|1[0-2])\2))(?:(?:1[6-9]|[2-9]\d)?\d{2})$|^(?:29(\/|-|\.)0?2\3(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))$|^(?:0?[1-9]|1\d|2[0-8])(\/|-|\.)(?:(?:0?[1-9])|(?:1[0-2]))\4(?:(?:1[6-9]|[2-9]\d)?\d{2})$/.test(dateEntered.valueOf());
    }
    else 
    {
        console.log("some fields blank");
        return 1;
    }

    //  return this.optional(element) || !isNaN(dateEntered.valueOf());

}, "Please enter a valid date");

var validator = $("#form1").validate({
rules: {
        date_of_birth_day: { datemultiple1: ["#date_of_birth_day", "#date_of_birth_month", "#date_of_birth_year"]},
        date_of_birth_month: { datemultiple1: ["#date_of_birth_day", "#date_of_birth_month", "#date_of_birth_year"]},
        date_of_birth_year: { datemultiple1: ["#date_of_birth_day", "#date_of_birth_month", "#date_of_birth_year"]},
    },        

    groups: {
        date_of_birth: "date_of_birth_day date_of_birth_month date_of_birth_year",
    },

    debug: true,

    messages: {
                    date_of_birth_year: {
                        required: "Please enter the day, month and year",
                        min: "Year must be 1900 or more"

                    },
                    date_of_birth_month: {
                        required: "Please enter the day, month and year",
                        min: "Month must be 1 or more",
                        max: "Month must be 12 or less"
                    },
                    date_of_birth_day: {
                        required: "Please enter the day, month and year",
                        min: "Day must be 1 or more",
                        max: "Day must be 31 or less"
                    }
    },
    errorPlacement: function(error, element) {
        switch (true) {

            case (element.attr("name")=="date_of_birth_day" || element.attr("name")=="date_of_birth_month" || element.attr("name")=="date_of_birth_year" ) :
                error.appendTo("#error_location_date_of_birth");
                break;

            default:
                // Append error within linked label
                $( element )
                error.appendTo("#error_location_"+ element.attr( "name" ));
                console.log("add to  ".concat(element.attr( "id" )));
                console.log("add to name ".concat(element.attr( "name" )));

        }
    },
        highlight: function(element, errorClass, validClass) {
        console.log("highlight ".concat(element.name));
        switch (true) {

            case (element.name=="date_of_birth_day" || element.name=="date_of_birth_month" || element.name=="date_of_birth_year" ) :
                //$("#form_group_date_of_birth").addClass("form-group--error");
                $(element).addClass("input--error");
                break;

            default:
                a2="#error_location_" + element.name + " span:first";
                $(a2).remove();
                $(element).parent().addClass("form-group--error");
                $(element).addClass("input--error");

                console.log("add class  ".concat(element.name));
        }
    },
        unhighlight: function(element, errorClass, validClass) {

        console.log("unhighlight " + element.name);
        switch (true) {
            case (element.name=="date_of_birth_day" || element.name=="date_of_birth_month" || element.name=="date_of_birth_year" ) :
                    //$("#form_group_date_of_birth").removeClass("form-group--error");
                    $(element).removeClass("input--error");
                    console.log("unhighlight dob day");
                break;

            default:
                $(element).parent().removeClass("form-group--error");
                $(element).removeClass("input--error");
                a2="#error_location_" + element.name + " span:first";
                $(a2).remove();

        }

    },
});

});

css

.form-group {
    margin-bottom: 30px;
}

.date-input__item {
    display: inline-block;
    margin-right: 20px;
    margin-bottom: 0;
}
.fieldset {
    margin: 0;
    padding: 0;
    border: 0;
}
.input--error {
    border: 4px solid #b10e1e;
}
.form-group--error {
    padding-left: 15px;
    border-left: 5px solid #b10e1e;
}

1 个答案:

答案 0 :(得分:-1)

jQuery Validate插件仅在用户与其交互时评估一个字段(或提交时的整个表单)。它无法知道您要在验证另外两个字段时评估验证规则。

您必须编写一个jQuery keyup和/或focusout处理函数,以编程方式在所需的时间和位置触发验证。使用附加到要触发此验证的字段的.valid()方法。

示例

$('.my_group_of_date_fields').on('keyup focusout', function() {
    $('.my_group_of_date_fields').each(function() {
        $(this).valid();
    })
});