Front End Developer

Add gift bag option to Shopify cart

Posted: 16 February 2022

Lorem ipsum dolor sit amet, consectetur adipiscing elit.

Praesent dictum blandit risus. Fusce maximus rhoncus dignissim.

document.addEventListener('DOMContentLoaded', (e) => {

  let formErrors = [];
  const errorTerms = '{{ "cart.general.agree_terms_error" | t  }}',
      errorDateValid = '{{ "cart.dob.error_date_valid" | t  }}';

  const clearErrors = () => {
    formErrors = [];
    let errors = document.querySelectorAll('[data-error]');
    errors.forEach(error =>{
      error.classList.remove('show');
      error.innerText = '';
    });
  }

  const showError = (field,errorText) => {
    let target = document.querySelector(`[data-error=${field}]`);
    target.classList.add('show');
    target.innerText = errorText;
  }

  const validateTerms = () => {
    const validateAgree = document.querySelector('#agree');

    if (!validateAgree.checked) {
      formErrors.push('Error');
      showError('agree', errorTerms);
    }

    //console.log(`Terms accepted: ${validateAgree.checked}`);

  }

  const validateDOB = () => {
    const validateFieldDOB = document.querySelector('#dobField'),
        minAge = 18;

    /* First check if date is valid */
    let validDOB = moment(validateFieldDOB.value, 'YYYY-MM-DD', true).isValid();
    //console.log(`Date of birth: ${validateFieldDOB.value} which means is ${validDOB}`);
    if (!validDOB) {
      formErrors.push('Error');
      showError('dob', errorDateValid);
    }

    /* If date is valid, check age*/
    /*
    if (validDOB) {
      let userDOB = moment(validateFieldDOB.value),
          today   = moment(),
          userAge = today.diff(userDOB, 'years');

      if (minAge <= userAge ) {
        console.log("The user is old enough");
      } else {
        console.log("The user is too young");
      }
    }
    */

  }

  const validateFields = (e) => {
    console.clear();
    clearErrors();
    validateTerms();
    validateDOB();

    if (formErrors.length > 0) {
      //console.log("There are some errors, not submitting form")
      e.preventDefault();
      return false;
    } else {
      cartForm.submit();
    }

  }

  const cartForm = document.querySelector('.cart-form');
  cartForm.addEventListener('submit', validateFields);

});