I need to test an input for proper date format. I want to accept several date formats so I created a validating function that test if at least one of the formats is OK and in that case return true. I use moment.js to test the date. When I simply type the condition with hard-coded string date formats, the function works properly:
var multiDateValidator = function (value)
{
if ((moment(value, 'DD/MM/YYYY', true).isValid()) ||
(moment(value, 'D/M/YYYY', true).isValid()) ||
(moment(value, 'DD.MM.YYYY', true).isValid()) ||
(moment(value, 'D.M.YYYY', true).isValid()) ||
(moment(value, 'DD. MM. YYYY', true).isValid()) ||
(moment(value, 'D. M. YYYY', true).isValid())) {
return true;
}
return false;
};
But if I want to use the list of allowed date formats, it doesn't work, it never returns true.
var allowedDateFormats = ['DD/MM/YYYY', 'D/M/YYYY', 'DD.MM.YYYY', 'D.M.YYYY', 'DD. MM. YYYY', 'D. M. YYYY'];
var multiDateValidator = function (value)
{
allowedDateFormats.forEach(function(dateFormat)
{
if (moment(value, dateFormat, true).isValid()) {
return true;
}
});
return false;
};
What's wrong with the second function? I know I'm not too good at JavaScript, but it should work, shouldn't it?
return true
is inside the 2nd one,return false
is in 1st one. If you addconsole.log("some text");
abovereturn true
, you will see what i mean. – Terminator