user1438611
user1438611

Reputation:

Javascript date of birth conundrum

I need to validate a primitive date of birth field input in the format of:

'mmmyyyy'

Where the first 3 characters of the string must be an acceptable 3-letter abbreviation of the months of the year. It can be lowercase, or uppercase, or a mix of any so long as it spells out jan or feb or mar etc etc etc. There is no built-in method that I am aware of that has a ready array of this specific format of a month to be able compare against user input. I was thinking that I could maybe use the localeCompare() method in a for loop to test if the output is not 0 then append an error message accordingly.

Upvotes: 0

Views: 204

Answers (4)

Neil
Neil

Reputation: 55402

new Date(str.replace(/(\D+)(\d+)/, "1 $1 $2"))

EDIT: use isNaN to test whether the date failed to parse.

Upvotes: 0

Jared Farrish
Jared Farrish

Reputation: 49208

Unless you just really, really want to check a month with a "dynamic" test, you can do:

var months = 'jan,feb,mar,apr,may,jun,jul,aug,sep,oct,nov,dec';

months.indexOf('JaN1975'.toLowerCase().substring(0,3)

Checking with:

console.log(months.indexOf('JaN1975'.toLowerCase().substring(0,3)) != -1);
console.log(months.indexOf('oct1975'.toLowerCase().substring(0,3)) != -1);
console.log(months.indexOf('FEB1975'.toLowerCase().substring(0,3)) != -1);
console.log(months.indexOf('Ja1975'.toLowerCase().substring(0,3)) != -1);
console.log(months.indexOf('091975'.toLowerCase().substring(0,3)) != -1);

http://jsfiddle.net/ELMFu/

Gives:

true
true
true
false
false

Upvotes: 0

gilly3
gilly3

Reputation: 91497

I like this concise function for validating your input:

var months = "janfebmaraprmayjunjulaugsepoctnovdec";
function validate(dateString) {
    return dateString.length == 7 &&
           !(months.indexOf(dateString.substr(0,3).toLowerCase()) % 3) &&
           isFinite(dateString.substr(3));
}

http://jsfiddle.net/gilly3/NR3aG/

Upvotes: 0

ErikE
ErikE

Reputation: 50241

function dateTester() {
   var d = new Date(),
      i,
      mo = [],
      moIsValid;
   for (i = 0; i < 12; i += 1) {
      d.setMonth(i);
      mo.push(d.toLocaleString().split(' ')[1].substr(0, 3));
   }
   return new RegExp('^(' + mo.join('|') + ')', 'i');
}

var moIsValid = dateTester();
alert(moIsValid.test('fEb1992'));

If you don't want the user's current locale name for the days to be valid, then just switch toLocaleString() to toString(). But then, why don't you just do this instead:

var moIsValid = /^(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)/i;
alert(moIsValid.test('fEb1992'));

Upvotes: 1

Related Questions