RegExp with react-imask not working - React, MUI, React-imask

832 Views Asked by At

I have an MUI TextField integrated with react-imask to mask as a GUID input. I entered a regex pattern in the mask prop but its not working. Please advice.

import './style.css';

import React, { forwardRef, FunctionComponent } from 'react';
import {
  InputBaseComponentProps,
  TextField,
  TextFieldProps,
} from '@mui/material';
import { IMaskInput } from 'react-imask';

interface ICustomOnChangeProp {
  onChange: (event: { target: { value: string } }) => void;
}

const TextMaskCustom = forwardRef<
  HTMLInputElement,
  Omit<InputBaseComponentProps, 'onChange'> & ICustomOnChangeProp
>(function TextMaskCustom(props, ref) {
  const { onChange, ...other } = props;
  return (
    <IMaskInput
      {...other}
      mask="/^[A-Za-z0-9]{8}-[A-Za-z0-9]{4}-[A-Za-z0-9]{4}-[A-Za-z0-9]{4}-[A-Za-z0-9]{12}$/"
      inputRef={ref}
      onAccept={(value: any) => onChange({ target: { value } })}
      lazy={false}
      placeholderChar="_"
      type="text"
    />
  );
});

const GuidInput: FunctionComponent<TextFieldProps> = (
  props: TextFieldProps
) => {
  return (
    <TextField
      {...props}
      InputProps={{
        inputComponent: TextMaskCustom as any,
      }}
    />
  );
};

export default GuidInput;

This is my stackblitz link.

Please advice.

1

There are 1 best solutions below

3
On

You should pass the regular expression to the mask props rather than string. See guide.html#masked-base and try RegExp demo at official site

<IMaskInput
  {...other}
  mask={
    /^[A-Za-z0-9]{8}-[A-Za-z0-9]{4}-[A-Za-z0-9]{4}-[A-Za-z0-9]{4}-[A-Za-z0-9]{12}$/
  }
  inputRef={ref}
  onAccept={(value: any) => onChange({ target: { value } })}
  lazy={false}
  placeholderChar="_"
  type="text"
/>

stackblitz