Matt
Matt

Reputation: 828

jquery validate rules apply even if input is not set as required

I'm running in to an issue regarding how rules are applied with jQuery validate.

If a rule for FirstName is declared, jQuery validate will trigger an validation error for that field even if the input does not have the required attribute set.

I'm running validation as a nested function in a jQuery form builder plugin. The plugin generates a form based on json data received from marketo. The reason for nesting the validation is so that the validation for several forms across several domains can be managed in one script.

The reason I'm querying how can I prevent rules from triggering it the required attribute is not applied to a form field is because of how marketo outputs the forms and the form names.

Example form:

<form action="" id="form" method="post">
  <div class="formrow">
    <label for="FirstName">First name: </label>
    <input type="text" name="FirstName" id="FirstName">
  </div>
  <input type="submit" value="submit">
</form>

Example validation:

  $('#form').validate({
    rules: {
      FirstName: {
        required: true
      }
    },
    messages: {
      FirstName: "Please enter your name"
    },
    submitHandler: function (form) {
      $(form).ajaxSubmit({
        error: function (response) {
          console.log(response);
        },
        success: function (response) {
          console.log(response);
        }
      });
    },
    errorElement: "em",
    errorPlacement: function (error, element) {
      error.appendTo(element.closest(".formrow").children("label"));
    }
  });

I've put together a demo to show the issue.

http://jsfiddle.net/onebitrocket/dzv5ugo0/

Upvotes: 0

Views: 2098

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337713

The required attribute is not on the element, but you have defined required: true in the rules object for FirstName, hence why the field is required. Remove the rules object for that element and it should work as you require.

Updated fiddle

Upvotes: 1

Related Questions