Created
April 13, 2021 14:35
-
-
Save tommylinks/3f4fc9654dd84d1b0ca831059241fd59 to your computer and use it in GitHub Desktop.
Input type text only numbers allowed (React hooks)
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 inputRegex = RegExp(`^\\d*(?:\\\\[.])?\\d*$`) | |
const escapeRegExp = (string) => { | |
return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') // $& means the whole matched string | |
} | |
const handleChange = (e) => { | |
const string = e.target.value | |
if(inputRegex.test(escapeRegExp(string))) { | |
setInputTest(string) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment