0

JS script for validating date format:

"date": {                    
                    //  Check if date is valid by leap year
            "func": function (field) {
                    //var pattern = new RegExp(/^(\d{4})[\/\-\.](0?[1-9]|1[012])[\/\-\.](0?[1-9]|[12][0-9]|3[01])$/);
                    var pattern = new RegExp(/([12]\d|0[1-9]|3[0-1])-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-\d{4}/);
                    var match = pattern.exec(field.val());
                    if (match == null)
                       return false;

                    /*var year = match[1];
                    var month = match[2]*1;
                    var day = match[3]*1;*/
                    var year = match;
                    var month = match[2];
                    var day = match[3];

                    var date = new Date(day, month - 1, year); // because months starts from 0.
                    return (date.getFullYear() == year && date.getMonth() == (month - 1) && date.getDate() == day);
                },                      
             "alertText": "* Invalid date, must be in DD-MM-YYYY format"
                },

Here, the regex has been changed to work with the format dd-M-yy. The regex is valid but it still shows the validation error when datepicker input is true.

How can I make the date format as dd-M-yy i.e 26-Nov-2014 and it gives no validations if the format is correct ?

Thanks.

Slimshadddyyy
  • 4,009
  • 2
  • 50
  • 104

1 Answers1

0

Try this:

var pattern = new RegExp(/([12]\d|0[1-9]|3[0-1])-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(\d{4})/);
var match = pattern.exec(field.val());
if (match == null)
 return false;

var months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
var year = match[3];
var month = match[2];
var day = match[1];

var date = new Date(day, month - 1, year); // because months starts from 0.
return (date.getFullYear() == year && date.getMonth() == months.indexOf(month) && date.getDate() == day);

http://jsfiddle.net/mw56tnej/12/

huwence
  • 318
  • 1
  • 8
  • It still shows the validation error. Datepicker input is `$(function(){ $( "#task_start_date").datepicker({ dateFormat: 'dd-M-yy' });` and class is `class="form-control validate[required,custom[date]]"` – Slimshadddyyy Nov 26 '14 at 10:11
  • could you create a jsfiddle with your code? I use pattern.exec("26-Nov-2014"), it return ["26-Nov-2014", "26", "Nov", "2014"]. – huwence Nov 26 '14 at 10:17
  • Yes the code seems correct, but can not figure out why its still giving validation even on expected input. – Slimshadddyyy Nov 26 '14 at 10:27
  • Maybe you should create a jsfiddle, I really don't know what is going wrong. Thanks. – huwence Nov 26 '14 at 10:55
  • `var isOk = (date.getFullYear() == year && date.getMonth() == months.indexOf(month) && date.getDate() == day); alert(isOk);` gives me `false` – Slimshadddyyy Nov 27 '14 at 09:38