-2

I am new to javascript. I am fixing bug programmed by others. I see validation code in javascript as:

 function validateTime(str) {
    var pattern = new RegExp(/^(([0-9])|([0-1][0-9])|([2][0-3])):(([0-9])|([0-5][0-9]))$/);
    if (pattern.test(str)) {
        return true;
    }
    else {
        return false;
    }
}

But it does't validate time:- 22-05-2015

How can it be done?

Tushar
  • 85,780
  • 21
  • 159
  • 179
  • It's not clear whether you are trying to validate a date or time: subject "*DateTIme*", function called "*validateTime*", text: "*…doesn't validate time*", example: "*22-05-2015*", which is a date. – RobG May 18 '15 at 07:26
  • 1
    Possibly a duplicate of [*How to validate a date?*](http://stackoverflow.com/questions/5812220/how-to-validate-a-date), but maybe not… – RobG May 18 '15 at 07:32

3 Answers3

2

You can use the Date object's parse method to verify a date string. You can then check if the value of Date.parse(str) is equal to "Invalid Date" to see if it is malformed. No need for regex at all.

Trinick
  • 21
  • 3
  • 1
    That only works if the string is in a format that is correctly parsed by the Date function in the browser being used. Until ES5, that was entirely implementation dependent. Now it **should** work for ISO 8601 format dates, but doesn't necessarily. The format in the OP will be treated differently by current browsers in use. – RobG May 18 '15 at 07:28
1

Your regex validates time, not date. To check against date in your format, use this:

var pattern = new RegExp(/^(0[1-9]|[12][0-9]|3[01])-(0[1-9]|1[012])-(19|20)\d\d$/);

You can check this pattern here:

https://regex101.com/r/kB5nV2/1

n-dru
  • 9,285
  • 2
  • 29
  • 42
  • Thanks alot!! Worked perfectly!! – Prakash Rai - ITH May 18 '15 at 07:26
  • 1
    @AlfonsoGarnett thanks, Indeed I omitted that slash, already put it back in place. As to separator, I assumed OP wants exactly this format, sure it could be enhanced to capture even more formats. – n-dru May 18 '15 at 07:31
  • 1
    @n-dru, no problem, fair enough! Prakash, you should pick an answer if your problem is solved. –  May 18 '15 at 07:52
0

function parseDate(str) {
  var m = str.match(/^(\d{1,2})-(\d{1,2})-(\d{4})$/);
  return (m) ? new Date(m[3], m[2]-1, m[1]) : null;
}

The function validateTime(str) used in your code is for time validation. Try the parseDate(str) for date validation.

Mohan Kumar
  • 102
  • 5