How to allow only numbers in textbox and format as US mobile number format in react js? ex : (224) - 5623 -2365
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 }); }}
import Input from '@material-ui/core/Input';
Use <Input type="number" />
instead.
In case you are using a form-validation library like react-hook-form, you can validateyour 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.