How can I validate a text input in react native for minimum characters

Viewed 20870

I have a text input for user to send a message. I want an error message to popup if the user enters less than 10 characters.

<TextInput
        style={styles.textArea}
        underlineColorAndroid="transparent"
        placeholder="Ask a question or comment"
        placeholderTextColor="grey"
        numberOfLines={1}
        textAlignVertical= 'top'
        multiline={true}
      />
3 Answers

You can validate on button onPress in TouchableOpactiy, TochablableHighlight. and also in onSubmitEditing prop with blurOnSubmit. Code is suggested on click of button.

onSubmit = () => {
    if (this.state.name.trim().length < 8) {
        Alert.alert('Alert', 'Password must be minimum 8 characters');
        return;
    }
    //Do your stuff if condition meet.
}

render() {
    return (
        <View style={{ flex: 1 }}>
            <TextInput
                style={{ height: 40, borderColor: 'gray', borderWidth: 1 }}
                onChangeText={(text) => this.setState({ password: text })}
                maxLength={16}
                secureTextEntry={true}
                value={this.state.password}
            />
            <TouchableOpacity onPress={() => this.onSubmit()}>
                <Text style={styles.submit}>Submit</Text>
            </TouchableOpacity>
        </View>

    )
}

You can add onChangeText={(text) => this.setState({messageText: text})} prop to save the entered text in your state. Then, you can have logic dependent on this.state.messageText.length, whether it's an onBlur event in the TextInput or if the user presses a submit button on the screen.

To display the error message, you can use Alert.alert().

You can use combination of onSubmitEditing prop with blurOnSubmit.

 state = {
   value: ''
 }

 onChange = (value) => this.setState({value})

 checkValue = () => {
   if(this.state.value.length < 10) { // ... Condition }
 }

 <TextInput
    ...
    blurOnSubmit={true}
    onChangeText={this.onChange}
    onSubmitEditing{this.checkValue}
  />
Related