score:16

Accepted answer

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 });
    }
}

score:-1

Set class on your Textfield:

<TextField type="number"
    inputProps={{className:'digitsOnly'}}
    floatingLabelText="mobileNumber"
    value={this.state.value}
    onChange={this.handleChange}
    id={"mobileNumber"} name={"mobileNumber"}
/>

You can apply a class on your Textfield that enables only numbers as follows:

$(".digitsOnly").on('keypress',function (event) {
    var keynum
    if(window.event) {// IE8 and earlier
       keynum = event.keyCode;
    } else if(event.which) { // IE9/Firefox/Chrome/Opera/Safari
       keynum = event.which;
    } else {
       keynum = 0;
    }

    if(keynum === 8 || keynum === 0 || keynum === 9) {
       return;
    }
    if(keynum < 46 || keynum > 57 || keynum === 47) {
       event.preventDefault();
    } // prevent all special characters except decimal point
}

Restrict paste and drag-drop on your Textfield:

$(".digitsOnly").on('paste drop',function (event) {
    let temp=''
    if(event.type==='drop') {
        temp =$("#mobileNumber").val()+event.originalEvent.dataTransfer.getData('text');
        var regex = new RegExp(/(^100(\.0{1,2})?$)|(^([1-9]([0-9])?|0)(\.[0-9]{1,2})?$)/g); //Allows only digits to be drag and dropped
        if (!regex.test(temp)) {
           event.preventDefault();
           return false;
        }
    } else if(event.type==='paste') {
        temp=$("#mobileNumber").val()+event.originalEvent.clipboardData.getData('Text')
        var regex = new RegExp(/(^100(\.0{1,2})?$)|(^([1-9]([0-9])?|0)(\.[0-9]{1,2})?$)/g); //Allows only digits to be pasted
        if (!regex.test(temp)) {
           event.preventDefault();
           return false;
        }
    }
}

Call these events in componentDidMount() to apply the class as soon as the page loads.

score:3

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.

score:3

Its really simple in MUI just add the line


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

score:12

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

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


Related Query

More Query from same tag