How to show error in Text Input in React Native

In this React Native source code example, the source code below illustrate how to show error in Text Input in React Native.

You can copy and adopt this source code example to your React Native project without reinventing the wheel.

import React, {Component} from 'react';
import { View,StyleSheet,TextInput,Text} from 'react-native';

export default class App extends Component {
  constructor(props) {
  super(props);
  this.state = { text: '', correct:true };
}
checkInput(text){
  this.setState({text})
  console.log(text.props)
  if (isNaN(text)){
    this.setState({correct:false})
  }
  else{
    this.setState({correct:true})
  }
}
    render() {
      const isCorrect =this.state.correct;
     return (
       <View style={styles.container}>
         <Text>Enter only Numbers</Text>
         <TextInput
           style={{backgroundColor: 'white',width:'60%',borderWidth: 1,borderColor: isCorrect?'green':'red'}}
           placeholderTextColor="#424242"
           onChangeText={(text) => this.checkInput(text)}
           value={this.state.text}
           />
         <Text>submit</Text>
       </View>
       );
   }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    padding: 25,
    justifyContent: 'center',
    alignItems:'center',
    backgroundColor: '#ededed',
  },
});

If you have any questions or suggestions kindly use the comment box or you can contact us directly through our contact page below.

 

Add a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.