Skip to content

Instantly share code, notes, and snippets.

@chrisjpatty
Last active April 6, 2024 15:27
Show Gist options
  • Save chrisjpatty/b0760e1973ca765e7a31d6be7d0ca861 to your computer and use it in GitHub Desktop.
Save chrisjpatty/b0760e1973ca765e7a31d6be7d0ca861 to your computer and use it in GitHub Desktop.
Javascript date Input mask MM/DD/YYYY
const maskDate = value => {
let v = value.replace(/\D/g,'').slice(0, 10);
if (v.length >= 5) {
return `${v.slice(0,2)}/${v.slice(2,4)}/${v.slice(4)}`;
}
else if (v.length >= 3) {
return `${v.slice(0,2)}/${v.slice(2)}`;
}
return v
}
@humberto1ortega
Copy link

humberto1ortega commented Oct 20, 2022

Great code. Seems to be the best solution I can find in regards to using javascript/typescript for masking a date. I have a slight suggestion Since I noticed that when you are at the fourth character typing it does not allow you to manually enter the '/' char which can be an issue. But if you change >=3 to just ==3 then that solves that issue and lets you enter the '/' manually at that point

const maskDate = value => {
let v = value.replace(/\D/g,'').slice(0, 10);
if (v.length >= 5) {
return ${v.slice(0,2)}/${v.slice(2,4)}/${v.slice(4)};
}
else if (v.length == 3) {
return ${v.slice(0,2)}/${v.slice(2)};
}
return v
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment