Skip to content

Instantly share code, notes, and snippets.

@nickfrosty
Created January 16, 2025 14:27
Show Gist options
  • Select an option

  • Save nickfrosty/e881a866117d359bb3d3d2883c106693 to your computer and use it in GitHub Desktop.

Select an option

Save nickfrosty/e881a866117d359bb3d3d2883c106693 to your computer and use it in GitHub Desktop.
🔥 tip (and a subtle ux improvement): if you require a url in a form, help the user get the url correct for validation - on focus -> auto insert the `https://` to start them off - on blur (and no full url) -> remove the prefix in order to show the placeholder again - when they paste in a url -> fix any duplicate http:// on either side of the inpu…
<Input
placeholder="https://my-project.com"
// this example was from using shadcn/ui forms
{...field}
onFocus={e => {
if (!e.target.value) form.setValue("website", "https://");
}}
onBlurCapture={e => {
if (
!e.target.value ||
e.target.value.match(/^https?:\/\/$/gi)
)
form.setValue("website", "");
}}
onChange={e => {
// sometimes the cursor is at the end
if (e.target.value.match(/^https?:\/\/https?:\/\//gi)) {
e.target.value = e.target.value.replace(
/^https?:\/\/https?:\/\//gi,
"https://",
);
}
// sometimes the cursor is at the beginning
else if (e.target.value.match(/(.*)https?:\/\/$/gi)) {
e.target.value = e.target.value.replace(
/https?:\/\/$/gi,
"",
);
}
// always fire the expected original `onChange`
field.onChange(e);
}}
/>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment