Skip to content

Commit

Permalink
Add qty rules client side validation to cart (Shopify#3471)
Browse files Browse the repository at this point in the history
  • Loading branch information
sofiamatulis authored May 15, 2024
1 parent f5e5566 commit 636b6b7
Showing 1 changed file with 41 additions and 6 deletions.
47 changes: 41 additions & 6 deletions assets/cart.js
Original file line number Diff line number Diff line change
Expand Up @@ -42,13 +42,48 @@ class CartItems extends HTMLElement {
}
}

resetQuantityInput(id) {
const input = this.querySelector(`#Quantity-${id}`);
input.value = input.getAttribute('value');
this.isEnterPressed = false;
}

setValidity(event, index, message) {
event.target.setCustomValidity(message);
event.target.reportValidity();
this.resetQuantityInput(index);
event.target.select();
}

validateQuantity(event) {
const inputValue = parseInt(event.target.value);
const index = event.target.dataset.index;
let message = '';

if (inputValue < event.target.dataset.min) {
message = window.quickOrderListStrings.min_error.replace('[min]', event.target.dataset.min);
} else if (inputValue > parseInt(event.target.max)) {
message = window.quickOrderListStrings.max_error.replace('[max]', event.target.max);
} else if (inputValue % parseInt(event.target.step) !== 0) {
message = window.quickOrderListStrings.step_error.replace('[step]', event.target.step);
}

if (message) {
this.setValidity(event, index, message);
} else {
event.target.setCustomValidity('');
event.target.reportValidity();
this.updateQuantity(
index,
inputValue,
document.activeElement.getAttribute('name'),
event.target.dataset.quantityVariantId
);
}
}

onChange(event) {
this.updateQuantity(
event.target.dataset.index,
event.target.value,
document.activeElement.getAttribute('name'),
event.target.dataset.quantityVariantId
);
this.validateQuantity(event);
}

onCartUpdate() {
Expand Down

0 comments on commit 636b6b7

Please sign in to comment.