Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add input verification #1657

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 43 additions & 1 deletion src/TimePicker/TimePicker.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,48 @@

/** Obtain a reference to the input HTML element */
export let ref = null;

export function timeValidator() {
// Check for invalid characters.
if (!/^[0-9:]*$/.test(value)) {
value = "";
return;
}

// Reject input that is too long.
// Return empty string here to avoid : insertion.
if (value.length > 5) {
value = value.slice(0, 2) + ":" + value.slice(2, 4);
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()) {
// Add missing colon if only hours are provided.
if (value.length === 2) {
value = value + ":00";
} else if (value.length === 1) {
value = "0" + value + ":00";
} else if (value.indexOf(":") === -1) {
value = value.slice(0, 2) + ":" + value.slice(2, 4);
}
// Check if hour is between 0 and 23.
const hour = Number(value.slice(0, 2));
if (hour < 0 || hour > 23) {
value = "";
return;
}
// Check if minute is between 0 and 59.
const minute = Number(value.slice(3, 5));
if (minute < 0 || minute > 59) {
value = "";
return;
}
}
}
</script>

<!-- svelte-ignore a11y-mouse-events-have-key-events -->
Expand Down Expand Up @@ -97,7 +139,7 @@
class:bx--text-input="{true}"
class:bx--text-input--light="{light}"
class:bx--text-input--invalid="{invalid}"
on:change
on:change="{timeValidator}"
on:input
on:keydown
on:keyup
Expand Down