Forked from intergalacticspacehighway/SyncTextInputValidation.tsx
Created
January 28, 2026 09:34
-
-
Save retyui/70b44734792e05f0e42de39075d19deb to your computer and use it in GitHub Desktop.
Synchronous validation with React Native TextInput
This file contains hidden or 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
| import { TextInput } from 'react-native'; | |
| import Animated, { | |
| useAnimatedRef, | |
| useHandler, | |
| dispatchCommand, | |
| useEvent, | |
| } from 'react-native-reanimated'; | |
| const AnimatedTextInput = Animated.createAnimatedComponent(TextInput); | |
| function ReanimatedTextInput() { | |
| const animatedRef = useAnimatedRef(); | |
| const handlers = { | |
| onChange: (event: any) => { | |
| 'worklet'; | |
| console.log('event', event); | |
| }, | |
| }; | |
| const { doDependenciesDiffer } = useHandler(handlers); | |
| const textInputHandler = useEvent( | |
| (event: any) => { | |
| 'worklet'; | |
| const { onChange } = handlers; | |
| if (onChange) { | |
| const textWithoutSpecialCharacters = event.text.replace(/[^a-zA-Z]+/g, ''); | |
| if (textWithoutSpecialCharacters !== event.text) { | |
| dispatchCommand(animatedRef, 'setTextAndSelection', [ | |
| event.eventCount, | |
| textWithoutSpecialCharacters, | |
| -1, | |
| -1, | |
| ]); | |
| } | |
| onChange(event); | |
| } | |
| }, | |
| ['onChange'], | |
| doDependenciesDiffer | |
| ); | |
| return ( | |
| <AnimatedTextInput | |
| style={{ height: 40, borderColor: 'gray', borderWidth: 1, marginTop: 100 }} | |
| onChange={textInputHandler} | |
| ref={animatedRef} | |
| /> | |
| ); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment