1

单击提交时,它会显示最后一个元素的错误消息(在这种情况下,“请选择您正在寻找的性别”并且在单击表单外的任何位置时,它会返回第一个元素的错误消息。我想要错误消息显示第一个无效元素。请参阅随附的代码。

$(function () {
    var form = $('.register form');
    var checkNameResult = $('#checkname-result');
    var validator = form.validate({
        errorPlacement: function (error, element) {
            checkNameResult.empty();
            checkNameResult.append(error);
        }
    });

    $('#Register_UserName').rules("add", {
        required: true,
        remote: "/account/IsUsernameAvailable",
        messages: {
            required: "Please enter a name",
            remote: "Name is not available"
        }
    });
    $("#Register_FirstName").rules("add", {
        required: true,
        messages: {
            required: "Please enter your first name"
        }
    });
    $("#Register_LastName").rules("add", {
        required: true,
        messages: {
            required: "Please enter your last name"
        }
    });


    $("#Register_Password").rules("add", {
        required: true,
        messages: {
            required: "Please enter a valid password"
        }
    });

    $("#Register_Email").rules("add", {
        required: true,
        email: true,
        messages: {
            required: "Please enter your email address",
            email: "Please enter a valid email address"
        }
    });

    $("#Register_Gender_Male").rules("add", {
        required: true,
        messages: {
            required: "Please select your gender"
        }
    });

    $("#Register_InterestedInMale").rules("add", {
        required: function (element) {
            return $('#Register_InterestedInFemale:checked').length == 0;
        },
        messages: {
            required: "Please select an Interested In gender"
        }
    });

    $("#Register_InterestedInFemale").rules("add", {
        required: function (element) {
            return $('#Register_InterestedInMale:checked').length == 0;
        },
        messages: {
            required: "Please select a gender you are Looking For"
        }
    });

    $('#checkname').click(function () {
        if (validator.element($('#Register_UserName')))
            checkNameResult.html("<label class='name-available'>Name is available</label>");
        return false;
    });

});
4

1 回答 1

0

好吧,我从不尝试验证这样的表格。

以这种方式使用 jquery.validation 插件:

$(".selector").validate({
    rules: {
        name: "required",
        email: {
            required: true,
            email: true
        }
    },
    messages: {
        name: "Please specify your name",
        email: {
            required: "We need your email address to contact you",
            email: "Your email address must be in the format of name@domain.com"
        }
   }
});

我已经使用 Symfony2、Wordpress、CodeIgniter 进行了测试。

于 2014-05-08T13:46:01.703 回答