check format of date with moment.js

rishi picture rishi · Feb 18, 2015 · Viewed 26.1k times · Source

I am taking input from calendar in my screen which is of this type

DD-MMM-YYYY HH:mm a

but user can provide date from keyboard. Now I have to check whether user has provided the date in correct format or not. I am heavily using moment.js in my application and validating it like this

 if(angular.equals(moment(scope.modelValue).format('DD-MMM-YYYY HH:mm a'), 'Invalid date'))
{
       alert('date is not correct');

}
else
{
alert('date is correct');
}

It is working fine but the problem is if I provide input like '18-Feb-2015 2' then it is converted to '18-Feb-2015 00:00 am'. so now how to check that format is exactly what I want ? please help ..

Answer

wallop picture wallop · May 16, 2017

if it's just for checking the below is a better alternative

moment(scope.modelValue, 'DD-MMM-YYYY HH:mm a', true).isValid()