Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to allow only numbers in textbox and format as US mobile number format in react js? ex : (224) - 5623 -2365

I am using React for mobile number validation. The TextField should allow only digits and it will format as US mobile number format. I am restricting to allow only digits, but the format is not happening. I am using material-ui for validation. Below my code.

import React from 'react';
import TextField from '@material-ui/core/TextField';

export default class myClass extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            value: '',
        };
        this.handleChange = this.handleChange.bind(this);
    }
    handleChange(e) {
        const re = /[0-9]+/g;
        if (e.target.value === '' || re.test(e.target.value)) {
            this.setState({ value: e.target.value });
        }
    }
    render() {
        return (
            <div>
                <TextField
                    floatingLabelText="mobileNumber"
                    onChange={this.handleChange}
                    value={this.state.value}
                />
            </div>
        );
    }
}
like image 863
Soumya Behera Avatar asked Mar 31 '17 06:03

Soumya Behera


4 Answers

import Input from '@material-ui/core/Input';

Use <Input type="number" /> instead.

like image 20
Yrineu Rodrigues Avatar answered Nov 10 '22 20:11

Yrineu Rodrigues


I have restricted the textbox to allow only numbers and formatted the mobile number as US mobile number format. Follow the below code.

handleChange(e) {
    const onlyNums = e.target.value.replace(/[^0-9]/g, '');
    if (onlyNums.length < 10) {
        this.setState({ value: onlyNums });
    } else if (onlyNums.length === 10) {
        const number = onlyNums.replace(
            /(\d{3})(\d{3})(\d{4})/,
            '($1) $2-$3'
        );
        this.setState({ value: number });
    }
}
like image 170
Soumya Behera Avatar answered Nov 10 '22 19:11

Soumya Behera


In case you are using a form-validation library like react-hook-form, you can validate your Textfield like this,

<TextField
     type="number"
     {...register("phonenum",{
         required: {
             value: true,
             message: 'Please fill this field',
         },
         pattern: {
             value: /^[1-9]\d*(\d+)?$/i,
             message: 'Please enter an integer',
         },
         min: {
             value: 1,
             message: 'Value should be atleast 1',
         },
   })}
   error={errors?.index ? true : false}
   helperText={errors?.index?.message}
/>

In case, you want to input phone numbers only, I would highly recommend to consider using react-phone-input-2.

like image 5
Nishant Kohli Avatar answered Nov 10 '22 19:11

Nishant Kohli


Its really simple in MUI just add the line


<TextField
type='number' //ad this line
onChange={(e) => setCode(e.target.value)} label="Enter otp" />

Along with that, you can allow numbers only in any textfield. Use like this:-

<UR_TEXT_INPUT_COMPONENT
value={code}
onChange={(e) => setCode(parseInt(e.target.value)} label="Enter otp" />
like image 4
hamid saifi Avatar answered Nov 10 '22 21:11

hamid saifi