使用jQuery验证自定义规则进行验证

时间:2016-03-02 13:41:46

标签: jquery jquery-validate

我有一个jQuery Validate的自定义验证规则。它应该防止用户插入大于车辆可用座位的乘客号码。如果插入的值错误,我启动的消息会弹出,但验证不会阻止我提交表单。问题是什么?

以下是代码:

$(function()
    {

        $.validator.addMethod("maxpass", function(value, element) {
                var del = "${requestScope.delete}";
                if (del == "true") {
                    return true;
                }
                var ret = "${requestScope.returnitinerary}";
                if (ret == "true") {
                    return true;
                }
                sum = 0;
                $("#vehicles :selected").each(function() {
                    $.ajax({
                        url : "${pageContext.request.contextPath}/vehicle/seatsno",
                        data : "id=" + $(this).val(),
                        async : false,
                        success : function(resp) {
                            sum += Number(resp);
                        }
                    });
                })
                 return (sum >= Number($("#passengersNo").val())) ;

            }, "Numero posti insufficiente!"),


            $("#itinerary").validate(
            {

                //validation rules
                rules :
                    {
                        departureDate : "required",

                        departureTime : "required",

                        arrivalDate : "required",

                        arrivalTime : "required",

                        arrivalCity : "required",
                        passengersNo :
                            {
                                maxpass : true,
                                required : true,
                                number : true
                            },
                        drivers :
                            {
                                required : true,
                                drive : true
                            },
                        vehicles : "required",
                        departureCity : "required",
                        serviceCost : "number",
                        transitPassCost : "number"
                    },

                //error messages
                messages :
                    {
                        vehicles : "Numero autisti non valido",
                    },

                submitHandler : function(form)
                    {
                        form.submit();
                    }
            });

    });

0 个答案:

没有答案