首页 > 解决方案 > 如何在本机反应中验证文本输入以获取最少字符

问题描述

我有一个文本输入供用户发送消息。如果用户输入少于 10 个字符,我希望弹出错误消息。

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

标签: validationreact-native

解决方案


您可以在TouchableOpactiyTochablableHighlight中的按钮 onPress 上进行验证。并且还在onSubmitEditing道具中使用blurOnSubmit。单击按钮时建议使用代码。

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>

    )
}

推荐阅读