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>
);
}
}
import Input from '@material-ui/core/Input';
Use <Input type="number" />
instead.
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 });
}
}
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.
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" />
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With