Constraints in the text field react

3

Is it possible for a text field to receive only the characters below?

numeros | espaço | barra (/) | traço (-)

The type field does not help me in this case, would it be nice to use the text type in this case?

    
asked by anonymous 19.07.2017 / 23:37

1 answer

0

You can use the onChangeText property of TextInput to filter what will be changed in your state local. Using the replace function ( string ) you can use a regular expression (example: /([^\d\s/-])/g ) to filter what the user is typing and remove everything that is:

  • Numbers
  • Spaces
  • Bar (/)
  • Hyphen (-)

Example:

constructor() {
    super();

    this.state = {
        text: '2015',
    };

    this.filterText = this.filterText.bind(this);
}

filterText(text) {
    this.setState({
        text: text.replace(/([^\d\s/-])/g, '')
    });
}

render() {
    return (
        <View>
            <TextInput
                style={{
                    height: 40,
                    width: '90%',
                    borderColor: 'gray',
                    borderWidth: 1
                }}
                onChangeText={this.filterText}
                value={this.state.text}
            />
        </View>
    );
}

Help material:

20.08.2017 / 09:34