Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to automatically takes a '/'(slash) in textInput field using react-native

I'm trying to add functionality to input mm/yy fields so as when the users enters 2 digits, slashes "/" get automatically added.

here's my TextInput

<TextInput
placeholder="mm/yy"
placeholderTextColor={Colors.BLACK_TRANSPARENT_50}
keyboardType="number-pad"
maxLength={4}
returnKeyType="done"
style={styles.secondtextinput}
></TextInput>
like image 716
Bledi Avatar asked Jan 25 '26 10:01

Bledi


1 Answers

I just did something like this in my app for adding a "-" in phone numbers :) It might be a bit of a roundabout fix, but here's what I did:

I used the useState hook to manage state in my functional component.

  const [date, setDate] = useState("");
                
  <TextInput
    onChangeText={(text) => {
      setDate(
        text.length === 3 && !text.includes("/")
          ? `${text.substring(0, 2)}/${text.substring(2)}`
          : text
      );
    }}
    placeholder="mm/yy"
    placeholderTextColor={Colors.BLACK_TRANSPARENT_50}
    keyboardType="number-pad"
    maxLength={5}
    returnKeyType="done"
    style={styles.secondtextinput}
    value={date}
  />

I changed the maxLength to 5 to account for the "/". As the user inputs the date, once it gets to a length of 3, it checks for any existing "/"s and, if there aren't any, it adds one in after the second character.

like image 112
FredAstaire Avatar answered Jan 27 '26 01:01

FredAstaire