Age Restriction on Checkout [solved]

  • Posts: 4
  • Thank you received: 2
2 weeks 11 hours ago #319212

-- HikaShop version -- : 4.2.3
-- Joomla version -- : 3.9.18
-- PHP version -- : 7.3.17
-- Browser(s) name and version -- : Firefox 76.0.1

To conform to local legislation, the wine sales website I am creating must record the buyers date of birth and ensure that the buyer is at least 18 years old before being able to complete a purchase.

I couldn't find any existing suggestions in the forums that worked sufficiently well for what I need so worked out the following solution for the jQuery UI date picker (the default date picker in the current version). I'm sure there are more elegant solutions but thought I should share this here for anyone else that gets stuck.

1. Create a custom "Date of Birth" field and:

set Field Type = Advanced date picker
set Required = Yes
set Format = %Y/%m/%d
set Allow = Only past dates
set Month selector = Yes
set Year selector = Yes
set Start = 1900

Note: you can set End = -18y so the year is only shown up to 18 years ago but this doesn't take into account the month or date when calculating whether someone is 18 year or older.

2. Add some custom jQuery to the start of the checkout show.php file for your template as follows (change "address_dob_input" to your own custom field name):

<script>
  jQuery(document).ready(function($) {
    $(document).ready(function(){
      $("#address_dob_input").datepicker();
      $("#address_dob_input").on('change', function(){
        var birthday = document.getElementById("address_dob_input").value;
        var dob = new Date(birthday);
        var today = new Date();
        var age = today.getTime() - dob.getTime();
        age = Math.floor(age / (1000 * 60 * 60 * 24 * 365.25));
        if (age < 18){
          alert('You must be over 18 years of age');
          $(this).val('');
        }
      });
    });
  });
</script>

References:

www.sitepoint.com/community/t/how-to-val...ry-datepicker/117179
stackoverflow.com/q/29137763

Last edit: 2 weeks 3 hours ago by ozneilau. Reason: Make it clearer to choose Advanced Date Picker
The following user(s) said Thank You: nicolas

Please Log in or Create an account to join the conversation.

Time to create page: 0.047 seconds
Powered by Kunena Forum