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

Viewed 1477

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>
2 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.

Problem with the above solution:

It adds a slash after text change i.e. When a user types the first digit of the year (third digit of expiry e.g. 10/2), then a slash will be inserted between the newly added digit and the previous digit i.e. When the user is done with the insertion of 2, then slash will be placed automatically between 0 and 2.

For a more elegant and robust solution, you can use this solution:

Create a component scoped variable:

let allowChangeText = true;

Then create a hook for expiry date text:

const [expiryDate, setExpiryDate] = useState('');

Later on use the component as:

<TextInput
   value={expiryDate}
   maxLength={5}
   keyboardType="number-pad"
   onKeyPress={({ nativeEvent }) => {
     if (nativeEvent.key == 'Backspace' && expiryDate.length == 3) {
        allowChangeText = false;
        setExpiryDate(expiryDate.substring(0, 2));
     } else {
        allowChangeText = true;
     }
   }}
   onChangeText={(text: string) => {
     if (allowChangeText) {
        setExpiryDate(text.length === 2 && text.indexOf('/') == -1
           ? `${text}/`
           : text
        );
     } else {
        console.log('change text is not of use!');
     }
   }}
 />
Related