-2

I'm using the jQuery validation plugin and I want make use of a custom method which takes data-min-date-adt and data-max-date-adt so that only dates in between are valid.

<input type="text" class="full-date required" data-age="adt" data-min-date-adt="22.04.2017" data-max-date-adt="22.04.2005">

Is there way to do this with this plug in?

Sparky
  • 98,165
  • 25
  • 199
  • 285
Kripton
  • 51
  • 1
  • 10
  • Search the documentation you linked for `custom validator` and have a look at this ► [https://jqueryvalidation.org/jQuery.validator.addMethod/](https://jqueryvalidation.org/jQuery.validator.addMethod/) - This should give you details on how to add custom validators. – Nope Feb 20 '17 at 12:19
  • I know about documentation, but I don't know how to implement that for this data attributes... – Kripton Feb 20 '17 at 12:21
  • then your question is, how to access data attributes? If so you can do it like this `$('input').data('minDateAdt')` Also see relevant jQuery documentation ► [https://api.jquery.com/data/](https://api.jquery.com/data/) – Nope Feb 20 '17 at 12:23
  • no fran, my question is how to validate dates as values... I don't understand how this plugin actually works and should I parse values to get it to work. Sorry I'm so confused about it and I'm newbie... – Kripton Feb 20 '17 at 12:28
  • 1
    To extract a data attribute value use `var dt1 = $('input').data('minDateAdt')`, to reverse the value for use in `new Date()` use `dt1 = dt1.split("").reverse().join("")`, To create a new date object do `var minDate = new Date(dt1)`, do the same with the other date data. To compare the date objects this should help ► [http://stackoverflow.com/questions/492994/compare-two-dates-with-javascript](http://stackoverflow.com/questions/492994/compare-two-dates-with-javascript) – Nope Feb 20 '17 at 12:39
  • Thank you very much, Fran! This helps a lot. – Kripton Feb 20 '17 at 12:45

1 Answers1

2

See the fiddle here: http://jsfiddle.net/w249x1ba/1/

$.validator.methods.adt = function(value, element) {
     var min = $(element).data('min-date-adt');
     var max = $(element).data('max-date-adt');

     var minDate = toDate(min);
     var maxDate = toDate(max);

    console.log(minDate);
    console.log(maxDate);

    var check = $(element).val();
    console.log(check);
    var checkDate = toDate(check);
    console.log(checkDate);

    function toDate(datestr) {
        var from = datestr.split(".");
        return new Date(from[2], from[1] - 1, from[0]);
    }

    var result = checkDate > minDate && checkDate < maxDate;
    console.log(result);
    return result;
};
Monzurul Shimul
  • 8,132
  • 2
  • 28
  • 42
  • Thank you very much shi! You helped me a lot! People downvoted my question, but all I needed is you solution... – Kripton Feb 21 '17 at 09:48