0

Issue: jQuery validation is not working on Safari but it does on Google chrome, firefox.

The CMS that handles the form to sign up need the date in the following format: YYYY-MM-DD. How people are used to fill in the form is like: DD-MM-YYYY. So i order to manage that i used jQuery (https://jqueryui.com/datepicker/). I set the correct date using dateFormat and used the altFormat to change the appearance of the date. When submitting the form, the validator method: minAge16 should check if the user is 16 years or older. When i test it on Google Chrome or Firefix, it works fine and return the error message; you are not 16 years or older. But when i test it on Safari browser or iPhone, it keeps saying you are not 16 years or older. My guess it that it doesn't work since safari makes use of a different time format. Has anyone else faced the validation problem in Safari or Chrome and how did you manage to find a work around?

jQuery Datepicker:

$(document).ready(function() {
   $( ".js-date-picker" ).datepicker({
      dateFormat: "yy-mm-dd",
      altFormat: "dd-mm-yy"
   });
});

The form:

<form action="" method="post" class="text-center py-4 js-validate" id="signup">
<div class="row">
    <div class="col-12 mb-2">
        <label class="input">
            <input type="text"
                   name="data[invoice][birthdate]"
                   placeholder="Date of birth*"
                   class="input__field js-date-picker mt-2" required value="">
        </label>
    </div>
</div>
<button type="submit" name="button" class="d-block mx-auto button mt-4 mt-lg-5">Submit</button>

Javascript:

$(document).ready(function() {
    // Check if browser supports date input
    var datePickerFormatMessage = '';
    var inputField = document.createElement('input');
    inputField.setAttribute('type', 'date');
    if(inputField.type != 'date') {
        datePickerFormatMessage = ' (JJJJ-MM-DD)';
    }

    // Check if the user entered a valid date
    $.validator.addMethod('validDate', function(value, element) {
        var regEx = /^\d{4}-\d{2}-\d{2}$/;
        if(!value.match(regEx)) {
            return false;  // Invalid format
        }

        var today = new Date();
        var date = new Date(value);
        if(Number.isNaN(date.getTime())) {
            return false; // Invalid date
        } else if ((today.getFullYear() - date.getFullYear()) > 110) {
            return false; // Invalid age
        }

        return date.toISOString().slice(0, 10) === value;
    }, ('Please enter a valid date' + datePickerFormatMessage));

    $.validator.addMethod('minAge16', function(value, element) {
        var birthDate = new Date(value);
        var eighteenYearsAgo = new Date();
        eighteenYearsAgo.setFullYear(eighteenYearsAgo.getFullYear() - 16);

        return (birthDate < eighteenYearsAgo);
    }, 'You must be atleast 16 years or older.');

    $('.js-validate').each(function() {
        $(this).validate({
            rules: {
                'data[invoice][birthdate]': {
                    validDate: true,
                    minAge16: true
                }

            },
            messages: {
                'data[buyer][birthdate]': {
                    date: 'Fill in a valid date' + datePickerFormatMessage
                }
            },

        });
    });
});

Here it goes wrong:

$.validator.addMethod('minAge16', function(value, element) {
    // here it goes wrong when i debug in safari, i am not getting a correct date back to check the difference
    var birthDate = new Date(value);
    var eighteenYearsAgo = new Date();
    eighteenYearsAgo.setFullYear(eighteenYearsAgo.getFullYear() - 16);

    return (birthDate < eighteenYearsAgo);
}, 'You must be atleast 16 years or older.');
Sparky
  • 98,165
  • 25
  • 199
  • 285
The M
  • 641
  • 1
  • 7
  • 33
  • Well, I'm on the real Safari 12 on a Mac High Sierra and your code is working fine for me: https://jsfiddle.net/v9g3t40h/ Where/how are you testing it in Safari? Are you actually using real Safari on a Mac, or are you using a simulator/emulator? If real Safari, what version? – Sparky Jul 21 '19 at 00:11
  • Also working perfectly in Safari on an iPhone Xs running latest iOS. – Sparky Jul 21 '19 at 00:26
  • @Sparky in the JsFiddle you are not using the jQuery datepicker plugin with dateFormat and altFormat options. That's why it is working. – The M Jul 21 '19 at 14:04
  • @Sparky i am using safari version 12.1.1, no emulators. – The M Jul 21 '19 at 14:06
  • Then logically it's not a validation issue despite your implication as such, but an issue with how the date-picker is handling the format. Since the latest version of jQuery UI is supposed to work fine in Safari, now I must ask you, what version of jQuery UI are you using? Since validation clearly works as expected when it gets proper input, I'd focus efforts solely on date-picker. – Sparky Jul 21 '19 at 14:24
  • @Sparky "jquery": "^3.3.1", "jquery-validation": "^1.17.0", – The M Jul 21 '19 at 14:39
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/196779/discussion-between-marc-and-sparky). – The M Jul 21 '19 at 17:33
  • Again, your problem cannot possibly have anything to do with jQuery Validate since that is working fine by itself. And what version of jQuery **UI** ? ... since this is where you're having the trouble, this should be the latest version. – Sparky Jul 22 '19 at 00:09
  • @Sparky jQuery UI version: 1.12.1. I think jQuery UI is returning a different format that can't be read correctly by jQuery validation. I am currently checking what jQuery UI returns. – The M Jul 22 '19 at 05:56
  • @Sparky i found a solution, i posted it as answer for this question :) – The M Jul 22 '19 at 13:25
  • I removed jQuery Validate tag since ultimately this had everything to do with Safari rejecting the date string format, and not the validation plugin or function. – Sparky Jul 22 '19 at 15:57

1 Answers1

0

Found the solution: Safari does not accept:

new Date('01-10-2000');

So what i did is:

var birthDate = new Date('01-10-2000'.replace(/-/g, "/"));

Afterwards i made sure that all dates have the correct format with UTCString();

birthDate.toUTCString();

This post helped me found the solution: Invalid date in safari

The M
  • 641
  • 1
  • 7
  • 33