1

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.

Lin Du
  • 88,126
  • 95
  • 281
  • 483
arunmmanoharan
  • 2,535
  • 2
  • 29
  • 60

1 Answers1

0

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

Lin Du
  • 88,126
  • 95
  • 281
  • 483
  • Thanks. I am unable to type in the inputbox. If I use the other regex, I am able to. Anything wrong with the regex I used? – arunmmanoharan Jul 12 '23 at 17:59
  • @arunmmanoharan A GUID regex: `/^(?:\{{0,1}(?:[0-9a-fA-F]){8}-(?:[0-9a-fA-F]){4}-(?:[0-9a-fA-F]){4}-(?:[0-9a-fA-F]){4}-(?:[0-9a-fA-F]){12}\}{0,1})$/` – Lin Du Jul 14 '23 at 03:40
  • https://stackblitz.com/edit/stackblitz-starters-fmcb6t?file=src%2FApp.tsx If you see here, the first two textFields are having the guid regex whereas the third one has a number regex. Only the number regex works. – arunmmanoharan Jul 14 '23 at 18:37