Hello there!
I'm trying to modify the default validation of a Datepicker, to avoid the following situation:
If I write down something like "blabla-404" when I change the focus to another element, the content is automatically transformed into "0404-01-01 00:00".
What I need is the content to be cleared.
I wrote a validator that looks like this:
(function (document, window, $) {
"use strict";
let DATATYPE_REGEX = {
'date': /(\d{4})-(\d{2})-(\d{2})/gm,
'time': /(\d{2}):(\d{2})/gm,
'datetime': /(\d{4})-(\d{2})-(\d{2})\s(\d{2}):(\d{2})/gm
};
$(".advancedDatePicker__base").each(function() {
let picker = $(this).find("coral-datepicker");
$(window).adaptTo("foundation-registry").register("foundation.validation.validator", {
selector: picker,
validate: dateFormatValidator
});
});
function dateFormatValidator(el) {
let picker = $(el);
let dataType = picker.attr("type");
let inputField = picker.find(".coral3-Textfield.coral-InputGroup-input");
let inputValue = inputField.val();
let regexValidation = new RegExp(DATATYPE_REGEX[dataType]).exec(inputValue);
if(regexValidation === null || !(dataType === "time" ? timeTypeValidator(regexValidation) : moment(inputValue).isValid())) {
inputField.val(undefined);
inputField.blur();
return;
}
}
function timeTypeValidator(regexValidation) {
let hour = parseInt(regexValidation[1]);
let min = parseInt(regexValidation[2]);
return (hour >= 0 && hour <= 23) && (min >= 0 && min <= 59);
}
})(document, window, Granite.$);
The problem is the validator is executed while the user types the date, creating some kind of weird situation deleting the picker content if the user types slowly.
I tried to run the validator when the input field change event is triggered but, at this point, the content is already changed as I said before.
Any clue about how to solve this? Thank you in advance.