-- 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
Edited 2nd June 2020:
Alternative Method using PHP
So the jQuery method works but after my client wanted to split the checkout into two steps, shoppers could go back to the first step, amend the date of birth and continue the checkout with a non-validated date.
So I came up with a way to check the DOB in PHP which I implemented instead of the jQuery solution also to the checkout show.php file:
<?php
if ($this->step == 2) {
$app = JFactory::getApplication();
$cart = $this->checkoutHelper->getCart();
if (is_string($cart->billing_address->address_dob)) {
$dob = strtotime($cart->billing_address->address_dob);
}
if(time() - $dob < 18 * 31556926) {
$message = "<h3><strong>You must be over 18</strong></h3><a href='/wines/checkout'>Click here</a> to go back to the previous page, click on the 'change guest information' button and check the date of birth you have entered<br />";
$app->enqueueMessage($message);
return;
}
}
?>
The code is only active on the second step of the checkout process. You will need to change the custom field name and the link as appropriate.