Michael BW
Michael BW

Reputation: 1070

Regex for testing date formatting

I found a very useful regular expression for testing format and content of a date field in a regex example site

BUT I get a validation when I put in dates older than 2000 and since this is a field for inputting date of birth you can see why it would be a problem. I am sure it is an easy fix but regular expressions intimidate me.

$('#txtDOB').blur(function() {
//$('span.error-keyup-5').remove();
var inputVal = $(this).val();
var dateReg = /^[0,1]?\d{1}\/(([0-2]?\d{1})|([3][0,1]{1}))\/(([1]{1}[9]{1}[9]{1}\d{1})|([2-9]{1}\d{3}))$/;
if(!dateReg.test(inputVal)) {
    alert('invalid date format: ' + inputVal);
}

I am not married to this solution so if you can suggest a better way please comment away.

Upvotes: 0

Views: 1384

Answers (3)

Mike Ryan
Mike Ryan

Reputation: 4374

There's a whole lot of mess there. First, eliminate all the {1}'s. That just means one instance, which is totally redundant. Also, a character class with one value is the same as the character itself. So, [1] becomes 1.

So, that leaves us with:

 /^[01]?\d\/(([0-2]?\d)|([3][01]))\/((199\d)|([2-9]\d{3}))$/

This is MM/DD/YYYY presumably. but the YYYY is just 199[0-9] and any year > 2000 and < 9999. Wow, that's a date range!

As a basic, try:

 /^[01]?\d\/(([0-2]?\d)|([3][01]))\/([12]\d{3}))$/

This gives a year range of 1000 - 2999. But as Tim said above, if you want really valid dates, you should use a specific date validator.

Upvotes: 2

Phrogz
Phrogz

Reputation: 303549

Instead of testing if a string matches one or more formats that you think might be good dates, I would suggest instead asking JavaScript if it thinks it is a valid date:

function isValidDate(str){
  return !isNaN(new Date(str));
}

This assumes that you're going to accept what the user gives you in any of a variety of formats (e.g. the horrid US MM/DD/YYYY or the more sane ISO8601 YYYY-MM-DD). If instead you have a specific format you will only accept, then parse your string based on that, pull out the year/month/date, and then ask JavaScript if this is a valid date:

function isValidDate(year, month, date) {
  var d = new Date(year*=1, month-=1, date*=1, 12);    // noon to skip DST issues
  return d.getFullYear()==year && d.getMonth()==month; // wrong date->wrong month
}

You need to check that the year/month/date all match because new Date(2011,11,32) is accepted and interpreted as 2012-1-1.

See also: Javascript method to ensure that a date is valid

Upvotes: 6

rtpHarry
rtpHarry

Reputation: 13135

If you need to parse date strings into dates then I would check out this library:

Upvotes: 1

Related Questions