0

I am completely new to react-native and have been trying to custom mask input. However, I am only getting numbers more than 10 even if I have specified the mask under TextInput. I am not sure what I am doing wrong. Your assistance will be greatly appreciated.

Please see my code below:

import React, { Component } from "react";
import { StyleSheet, SafeAreaView, TextInput } from "react-native";


export default class InputMask extends Component {

    state = {
        mask: '',
    }

    customMask = (mask) => {
        if ( typeof mask == 'String') {
            for (let i = 0; i < mask.length; i++) {

                if ( mask == '9') {
                    return mask.replace(/[^0-9]+/g, '')
                }
                if ( mask == 'a') {
                    return mask.replace(/[^a-zA-Z]+/g, '')
                }
                if ( mask == 's') {
                    return mask.replace(/[^a-zA-Z0-9]+/g, '')
                }
                if ( mask == '*') {
                    return mask
                }
            }
        }
        this.setState({
            mask: mask.substring(0, mask.length) || ''
        })
    }

    render() {

        return (
            <SafeAreaView style={styles.container}>
                <TextInput
                    mask= '(999) 999 9999'
                    placeholder="Enter phone number"
                    value={this.state.mask}
                    onChangeText={this.customMask}
                    style={styles.input}
                    keyboardType="phone-pad"

                />
            </SafeAreaView>
        );
    }
}


const styles = StyleSheet.create({
    container: {
        flex: 1,
        justifyContent: "center",
    },
    input: {
        height: 40,
        margin: 12,
        borderWidth: 1,
        padding: 10,
    },
});
Skyy
  • 1
  • 1
  • 2

1 Answers1

0

Firstly seems like the mask props you are trying to pass to RN TextInput are not available you can look through here to see available props. Secondly, seems like the way you are approaching is not the way you want to proceed I recommend you understand how and what the props for text input give and do then start creating a custom component. For your masked input you can external libraries like this (not promoting just an example) as they exist to make our lives easier but if you are still keen on making custom components you can browse through their GitHub repo and see on how they have implemented it and try something similar like this.

Mandip Giri
  • 411
  • 3
  • 10
  • Thank you so much for your answer. I have to implement a custom mask input for an existing huge codebase for a mobile application and they are trying not to use libraries. – Skyy May 23 '22 at 10:14