Open
Description
It would be very convenient to have something like the code below being part of the TimePicker component.
function processTimeString(time: string): string {
// Check for invalid characters.
if(!/^[0-9:]*$/.test(time)){
return "";
}
// Reject input that is too long or short.
// Return empty string here to avoid : insertion.
if(time.length > 5 || time.length == 0){
return "";
}
// Regular expression to check if time is in hh:mm format.
const timeFormat = /^([0-1]?[0-9]|2[0-3]):[0-5][0-9]$/;
// Check if time is in hh:mm format.
if (!timeFormat.test(time)) {
// Add missing colon if only hours are provided.
if (time.length === 2) {
time = time + ":00";
} else if (time.length === 1) {
time = "0" + time + ":00";
} else if (time.indexOf(':') === -1) {
time = time.slice(0, 2) + ":" + time.slice(2);
}
// Check if hour is between 0 and 23.
const hour = Number(time.slice(0, 2));
if (hour < 0 || hour > 23) {
return "";
}
// Check if minute is between 0 and 59.
const minute = Number(time.slice(3, 5));
if (minute < 0 || minute > 59) {
return "";
}
}
return time;
}
Activity
theetrain commentedon Jan 13, 2023
Thanks for the suggestion! It looks like the supplied function performs input masking, and I couldn't find information on Carbon's official stance on input masking. It appears that input masking should be suggested, but not enacted as part of an input's
helperText
—which TimePicker seems to be missing.It's implied that formatting user input while typing causes screen reader issues, but is acceptable on
blur
. If you're interested in having input masking while typing be supported by Carbon components, I suggest opening an issue in the flagship repository https://github.com/carbon-design-system/carbon/I think formatting on
blur
should be an acceptable enhancement now since DatePicker does that today.References:
gohde commentedon Jan 13, 2023
It is not meant to run
onKeyUp
, I run the above functiononChange
hooked up to the input reference of the component, it only needs to run when the user is done inputting and has actually made a change. This is to make it consistent with the DatePicker which I have next to it in the form. Although DatePicker runs onBlur I think.gohde commentedon Jan 13, 2023
From a UX perspective I find
onChange
better for form validation. It gives the user a chance to do things before nagging her or him to fix stuff. I prefer then to run all validators on submission to catch any un-changed required fields that the user didn't fill out.theetrain commentedon Jan 13, 2023
I agree, running this
onChange
sounds good to me; and your UX opinion aligns with me and Carbon guidelines: https://carbondesignsystem.com/patterns/forms-pattern/#behavior