Reputation: 476659
moment.js
can format time according to a given format.
Some formats however seem invalid. For instance the website provides the YYYY [escaped] YYYY
format. When one however specifies YYYY [escape
, the time is formatted like 2014 [121campe
its clear that e
and s
are converted according to the formatting guidelines, but the format is quite invalid.
Is there a way to check if the format provided is valid and for instance if some aspects will be shown in the resulting string (example format.containsHours, note this should also return true if not HH
is part of the format string, but for instance LLLL
will print the hours implicitly).
I've found nothing in the documentation thus far.
Upvotes: 2
Views: 4164
Reputation: 19
Use this function
function checkIfDateIsValidUsingMoment(dateString,format)
{
var m=moment(dateString,format);
return m._pf.charsLeftOver ==0 && m._pf.unusedTokens.length==0 && m._pf.unusedInput.length==0 && m.isValid();
}
Above function takes datestring and format, Moment object has isvalid
method but its less usable for strict date validation.
Moment Object has _pf
which stores info about parsed date.
charsLeftOver
: no of chars that do not match (Means extra character, invalid date)
unusedInput
: array containing details about unused inputs
unusedTokens
: array containing details about unused tokens
For ex :
moment("25 october 2016aaaa","DD MMM YYYY")
This object has "aaaa" as invalid character so it is available in _pf
object
You can validate date using these details.
Upvotes: 1
Reputation: 1580
This could work:
function isValidDate(date) {
return (moment(date).toDate().toString() !== "Invalid Date")
}
Upvotes: 1
Reputation: 241525
Moment's validation functions are limited to validating whether a given date/time input string is valid according to a given format. It is assumed that the format(s) are known to the developer. It's not intended to accept the format string itself from a variable source such as the end user.
So no, there are no methods for confirming that the format string is valid.
Upvotes: 2