I'm trying to parse, validate and re-format dates in an HTML form using moment.js. Because the website is being used internationally I want to reformat the dates in D MMM YYYY format (eg: 1 Apr 2018) to minimise any confusion once they've been entered.
The textboxes in my code are defined as follows:
<input type="text" class="txt-date" name="foo" />
And the JavaScript I've written to do the validation/re-formatting is as follows:
$(function () {
console.log("initial locale: " + moment.locale());
console.log("initial date format:= " + moment.localeData().longDateFormat('L'));
var locale = window.navigator.userLanguage || window.navigator.language;
console.log("changing locale to: " + locale);
moment.locale(locale);
console.log("updated locale: " + moment.locale());
console.log("updated date format = " + moment.localeData().longDateFormat('L'));
$('input.txt-date').on('change', function() {
var v = $(this).val();
if (!v) return; // No value in the textbox
v = moment(v); // Parse the date
if (!v.isValid) {
alert("Invalid Date!");
return;
}
// Re-format the date
$(this).val(v.format("D MMM YYYY"));
});
});
Here's the output in the browser's log:
initial locale = en
initial date format = MM/DD/YYYY
changing locale to: en-GB
updated locale: en
updated date format = MM/DD/YYYY
Essentially, moment.js seems to assume that I should be using English (US) regional settings, rather than English (UK). Changing the locale (as shown here) based on the user language seems to have made no difference.
All I want to do is to be able to parse date strings in either the user's local/regional format (or D MMM YYYY if they enter it that way). Can anyone provide any pointers?
Solution
Thanks to Phani for the help. In order to get this working you'll need to include the moment-with-locales.js file (which can be found at "https://momentjs.com/downloads/moment-with-locales.js" but is also included in the NuGet package).
The updated JavaScript is as follows:
$(function () {
// Configure moment to use the user's locale
moment.locale(window.navigator.userLanguage || window.navigator.language);
$('input.txt-date').on('change', function () {
var v = $(this).val();
if (!v) return; // No value in the textbox
// Parse the date specified
var fmt = moment.localeData().longDateFormat('L');
v = moment(v, [fmt, "D MMM YY", "D MMM YYYY"]);
// If the date is invalid, warn the user
if (!v.isValid()) {
alert("Invalid Date!");
return;
}
// Re-format the date
$(this).val(v.format("D MMM YYYY"));
});
});
This combination has worked with every valid date I've could throw at it.