我正在使用jQuery验证插件验证我的表单.它工作(放置错误消息,旁边的无效输入,这拧紧了我的设计),但我想为每个输入字段指定错误容器.我发现了errorLabelContainer,但这会将所有错误放在一个容器中.
让我们说,我有2个输入,一个是id名字,一个是名字.我们还假设我有2个错误跨度,其中包含ids errorName和errorFirstname.如何告诉jQuery将名称的验证错误写入带有id errorName的span中.
这是我目前的jQuery:
$("#form").validate({ errorLabelContainer: "#errors",rules: { name: { required: true },firstname: { required: true } },messages: { name: { required: "Enter name" },firstname: { required: "Enter firstname" } } })
解决方法
我认为errorPlacement选项适合您的需要:
Customize placement of created error labels. First argument: The created error label as a jQuery object. Second argument: The invalid element as a jQuery object.
您可以根据无效元素确定要放置错误的元素:
$("#form").validate({ rules: { name: { required: true },firstname: { required: true } },messages: { name: { required: "Enter name" },firstname: { required: "Enter firstname" } },errorPlacement: function ($error,$element) { var name = $element.attr("name"); $("#error" + name).append($error); } });