rolo
rolo

Reputation: 543

React, how to use maskInput without allowing empty spaces

Im using material-ui TextField component and Im having a hard time trying to make that only allow numbers in Firefox, I have seen some workarounds but I can't make it work. The closest I was to achieving this was using a mask like this:

           <Mui.TextField
                  margin="normal"
                  fullWidth         
                  value={values.adrNumber}
                  onChange={handleChange}
                  onBlur={handleBlur}
                  name="adrNumber"
                  InputProps={{
                    inputComponent: numberMask,
                  }}
                  label={t('adr_number')}>
                </Mui.TextField>   

Where numberMask is:

import React, { Component } from "react";
import MaskedInput from "react-text-mask";

export class NumberMask extends Component {

  render() {
    const { inputRef, ...other } = this.props;
    return (
      <MaskedInput
        {...other}
        ref={ref => {
          inputRef(ref ? ref.inputElement : null);
        }}
        mask={[/^[0-9]*$/,/^[0-9]*$/,/^[0-9]*$/,/^[0-9]*$/,/^[0-9]*$/,/^[0-9]*$/,/^[0-9]*$/,/^[0-9]*$/]}
        placeholderChar={'\u2000'}
      
      />
    );
  }
}

With this I could achieve to just allowing numbers, the problem is that I could write inputs like the following ones:

input1: 5632 59

input2:1 56 8563

Actually it doesn't allow typing with the keyboard blank spaces, but with the mouse you could possisionate wherever you want and start typing.

For example, I start writing 3 numbers:

658|

Then with the mouse I possisionate two spaces to the right:

658 |

And write two more numbers:

658 32|

Is there a way to avoid this problem? or even better, how could I do to just allow number in this mui component in Firefox?

Thanks

Upvotes: 0

Views: 1306

Answers (1)

Piyush Rana
Piyush Rana

Reputation: 667

You can try this inside your handleChange:

const value = e.target.value;        
const regExMatch = value.match(/^\d+$/);
        
props.setFieldValue(
   'adrNumber',
    regExMatch ? value : value.substr(0, value.length - 1),
)

Note: setFieldValue is a function provided by formik to set a particular field's value

Upvotes: 1

Related Questions