Last active
April 6, 2024 15:27
-
-
Save chrisjpatty/b0760e1973ca765e7a31d6be7d0ca861 to your computer and use it in GitHub Desktop.
Javascript date Input mask MM/DD/YYYY
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} |
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
Thank you