Jquery验证在提交时丢失样式

时间:2017-04-27 16:36:20

标签: jquery css jquery-validate

我正在使用jquery validate插件,当提交表单时,样式会丢失。

他们只是变得笨拙!

我希望表单在提交表单之前保持原样。

附件是截图和代码:

<script src="https://cdn.jsdelivr.net/jquery.validation/1.15.1/jquery.validate.min.js"></script>

<style>
.label {
  width:100px;
  text-align:right;
  float:left;
  padding-right:10px;
  font-weight:bold;
}
#ats_fellow_application_payment_form label.error {
  color:#FB3A3A;
  font-weight:bold;
  padding: 10px;
}

#ats_fellow_application_payment_form input.error {
  color:#FB3A3A;
  font-weight:bold;
  padding: 0px;
}

h1 {
  font-family: Helvetica;
  font-weight: 100;
  color:#333;
  padding-bottom:20px;
}
</style>


<script type="text/javascript">
// Wait for the DOM to be ready
$(function() {
  // Initialize form validation on the registration form.
  // It has the name attribute "registration"
  $("form[name='ats_fellow_application_payment_form']").validate({
    // Specify validation rules
    rules: {
      // The key name on the left side is the name attribute
      // of an input field. Validation rules are defined
      // on the right side
      firstname: "required",
      lastname: "required",
      email: {
        required: true,
        // Specify that email should be validated
        // by the built-in "email" rule
        email: true
      }
    },
    // Specify validation error messages
    messages: {
      firstname: "Please enter your firstname",
      lastname: "Please enter your lastname",

      email: "Please enter a valid email address"
    },
    // Make sure the form is submitted to the destination defined
    // in the "action" attribute of the form when valid
    submitHandler: function(form) {
      form.submit();
    }
  });
});
</script>


<form  method="POST" name="ats_fellow_application_payment_form" id="ats_fellow_application_payment_form" novalidate="novalidate">   
    <div class="label">First Name</div><input type="text" id="firstname" name="firstname" /><br />
    <div class="label">Last Name</div><input type="text" id="lastname" name="lastname" /><br />
    <div class="label">Email</div><input type="text" id="email" name="email" /><br />
    <div style="margin-left:140px;"><input type="submit" name="submit" value="Submit" /></div>
</form>

Before and After View of the Form

1 个答案:

答案 0 :(得分:0)

您的代码有效。这是一个CSS问题。我建议删除label.error上的顶部/底部填充,并删除或更新input.error。根据您的图像显示,错误标签中添加了其他样式,但未包含在您提供的代码中。

或者,您可以使用errorContainer,errorLabelContainer和validate的包装选项将错误消息添加到错误容器中来更改错误消息的位置。您还可以使用以下命令将错误消息附加到元素以控制样式和位置:

errorPlacement: function (error, element) {
    error.appendTo(element.siblings('span.errorMsg'));
}

有关这些选项的其他信息,请参阅docs

工作fiddle