mobile number validation accept numeric

Allow only numbers in Input in React | Regex and Number

Use value and onChange property of input field to allow only numbers in text-box.
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. 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}
                />
            </>
        );
    }
}

export default AllowOnlyNumber;

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;

ANIL SINGH

Anil Singh is an author, tech blogger, and software programmer. Book writing, tech blogging is something do extra and Anil love doing it. For more detail, kindly refer to this link..

My Tech Blog - https://www.code-sample.com/
My Books - Book 1 and Book 2

www.code-sample.com/. Powered by Blogger.
^