2

Yes I know there is this post

But how do you do address validation in the frontend of Commerce 3?

The problem is the way Billing Address & Shipping Address are set up. Billing Address are the same form fields duplicated via js and it is next to impossible to differentiate the two.

If I add required to any field this will also apply to the hidden field in the billing address form. Therefore, the html5 validation will always fail.

Has anybody a solution to this?

2 Answers 2

2

Would removing required via JS be an option?

1

Found a solution. I just add or remove the html5 required tag on load via Javascript. This way the js who duplicates the form can do whatever it wants and the html remains untouched:

// adds required tag to inputs on page load
  $("#shippingAddress-firstName").attr("required", "");
  $("#shippingAddress-lastName").attr("required", "");
  $("#shippingAddress-address1").attr("required", "");
  $("#shippingAddress-zipCode").attr("required", "");
  $("#shippingAddress-city").attr("required", "");
  $(".js-address-country").attr("required", "");

  // listens to billing address checkbox
  $("#billingAddressSameAsShipping").change(function () {
    if ($(this).is(":checked")) {
      //removes required attributes when checkbox is checked (billing address form invisible)
      $("#billingAddress-firstName").removeAttr("required");
      $("#billingAddress-lastName").removeAttr("required");
      $("#billingAddress-address1").removeAttr("required");
      $("#billingAddress-zipCode").removeAttr("required");
      $("#billingAddress-city").removeAttr("required");
      $(".js-address-country").removeAttr("required");
    } else {
      //adds required attribute when checkbox is unchecked (billing address form visible)
      $("#billingAddress-firstName").attr("required", "");
      $("#billingAddress-lastName").attr("required", "");
      $("#billingAddress-address1").attr("required", "");
      $("#billingAddress-zipCode").attr("required", "");
      $("#billingAddress-city").attr("required", "");
      $(".js-address-country").attr("required", "");
    }
  });

Aditionaly the required tag is added or removed based on the Billing address checkbox.

This can be written much better I'm sure.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.