Add Max Length Validation on TextInput in React Native

Hello friends, In today’s tutorial we would learn about implementing max length validation on TextInput component of react native. In few of mobile applications we have seen that user can enter a certain amount of string characters in a TextInput box. After that it will restrict the user to typing more characters. Now how it is possible to control the input? So in TextInput component we have a prop named as maxLength={ }, In which we can define how many characters we want to get from user. So it controls that but the next thing is notify user using a Alert dialog box that He cannot enter more than specified characters in the input box. To solve this problem we’re using onChangeText={} method of TextInput. The onChangeText={} calls each time when user enter a single character. So in this tutorial we would learn about Add Max Length Validation on TextInput in React Native.

Contents in this project Add Max Length Validation on TextInput in React Native :-

1. Open your project’s main App.js file and import Alert, StyleSheet, SafeAreaView, TextInput and Text component.

2. Creating our main App component.

3. Creating a function named as onReach_MAX_Length() with temp argument. So we would call this function on onChangeText={} event and in the function we would simply calculate the String length using Length function of String. When length of string reaches to our given length then we simply show a Alert.

4. Creating return() block, Here we would make our main TextInput component with maxLength={12}
and onChangeText={item => onReach_MAX_Length(item)} .

5. Creating Style.

6. Complete Source Code for App.js File :-

Screenshots :-

Add Max Length Validation on TextInput in React Native

Leave a Reply

Your email address will not be published. Required fields are marked *