DEV Community

Anil Singh
Anil Singh

Posted on

Allow only numbers in Input in React

Use value and onChange property of input field to allow only numbers in textbox.
Inside the onChange handle check whether the entered value is valid number or not. Update the state only when entered value is a valid number.

Alt Text

See the below example to do this.

Example 1,

You can use Number and conditionally change state.

import React, {
    Component
} from 'react';

class AllowOnlyNumber extends Component {
    constructor(props) {
        super(props);

        this.state = {
            telephone: ''
        };
        this.onHandleTelephoneChange = this.onHandleTelephoneChange.bind(this);
    }

    onHandleTelephoneChange = e => {
        let telephone = e.target.value;

        if (!Number(telephone)) {
            return;
        }
        this.setState({
            [e.target.name]: telephone
        });
    };

    render() {
        return ( <
            >
            <
            label > Allow only numbers in Input(React): < / label > <
            input type = "tel"
            name = "telephone"
            placeholder = "Telephone Number"
            value = {
                this.state.telephone
            }
            onChange = {
                this.onHandleTelephoneChange
            }
            / > <
            />
        );
    }
}

Example 2,

You can use regex and conditionally change state.

import React, { Component } from 'react';

class AllowOnlyNumber extends Component {
    constructor(props) {
        super(props);
        this.onHandleTelephoneChange = this.onHandleTelephoneChange.bind(this);  
        this.state = {
            telephone: '',
            regexp : /^[0-9\b]+$/
        }   
    }
    
    onHandleTelephoneChange = e => {
        let telephone = e.target.value;

        // if value is not blank, then test the regex
        if (telephone === '' || this.state.regexp.test(telephone)) {
            this.setState({ [e.target.name]: telephone })
        }
    };

    render() {
        return (
            <>
                < label >Allow only numbers in Input (React) : </ label >
                < input
                    type="tel" name="telephone" placeholder="Telephone Number"
                    value={this.state.telephone}
                    onChange={this.onHandleTelephoneChange}
                / >
            </>
        );
    }
}
export default AllowOnlyNumber;

Explore other examples, 65 Best FAQs and Examples

Top comments (2)

Collapse
 
dance2die profile image
Sung M. Kim

Hi Anil,

Could you format/highlight code snippets in this article, as well by referring to the Editor Guide?

Collapse
 
anilsingh profile image
Anil Singh

Actually, I am new here. wen I get time i will try to do the same.