Implementing a Numeric-Only TextInput in React Native

Implementing a Numeric-Only TextInput in React Native

17 December 2024 Stephan Petzl Leave a comment Tech-Help

In mobile app development, ensuring that user inputs are valid and as expected is crucial. One common requirement is to allow only numeric input in a TextInput field in React Native. This article will guide you through various methods to achieve this, focusing on the most efficient and up-to-date solutions.

Challenges with Numeric Input

While setting the keyboardType to ‘numeric’ can prompt the numeric keyboard, it doesn’t prevent users from pasting non-numeric characters. Therefore, additional validation is necessary to ensure input integrity.

Using Regular Expressions for Validation

A highly efficient method to filter input is using a regular expression. This approach is both concise and performant. Here’s a practical example:

      
        onChanged(text) {
          this.setState({
            mobile: text.replace(/[^0-9]/g, '')
          });
        }
      
    

This function replaces any non-numeric character with an empty string, leaving only the numbers, thus ensuring that your TextInput accepts only numeric input.

Alternative Approaches

Limiting Input Length

To further control user input, you can set a maximum length for the input:

      
         this.onChanged(text)}
          value={this.state.myNumber}
          maxLength={10} // Limit input to 10 digits
        />
      
    

Creating Reusable Components

For a more reusable solution, consider creating a custom component that encapsulates this functionality. This approach promotes code reuse and maintainability.

Practical Example

Below is a complete example implementing a numeric-only TextInput using the discussed methods:

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

        const NumericTextInput = () => {
          const [text, setText] = useState('');

          const handleTextChange = (inputText) => {
            const numericText = inputText.replace(/[^0-9]/g, '');
            setText(numericText);
          };

          return (
            
              
            
          );
        };

        const styles = StyleSheet.create({
          container: {
            flex: 1,
            justifyContent: 'center',
            alignItems: 'center',
          },
          input: {
            width: 200,
            height: 40,
            borderWidth: 1,
            borderColor: 'gray',
            paddingHorizontal: 10,
          },
        });

        export default NumericTextInput;
      
    

Enhancing Testing with Repeato

When developing mobile applications, testing is as critical as the development itself. Tools like Repeato can streamline your testing process. Repeato is a no-code test automation tool for iOS and Android, offering fast test creation and execution using computer vision and AI. It can be particularly beneficial for React Native apps by ensuring that your numeric input validations function correctly across different devices and scenarios.

Like this article? there’s more where that came from!