'React-Hooks-Forms: Why when copy-paste correct digits number lenght that triggers the min/max lenght validation

In my React app, I'm using the react-hook-form inside a Material UI v5 TextField input. This input is used to validate a 6 digits number code length.

When I copy-paste the numbers the validation is triggered and the error come ups as per the screenshot and I have no idea how to fix it

the error occurs when I copy a number as 123 456 which is formatted by the below script handleFormatCode to 123456 on the onChange trigger.

I'm without ideas on what causing this issue and how to solve it.

Error

The code involved in this input as

<TextField
            id="token"
            name="token"
            autoComplete="off"
            autoFocus
            label={
              <FormattedMessage defaultMessage="Please enter your 2FA token" />
            }
            placeholder="### ###"
            inputRef={register({
              maxLength: {
                value: 6,
                message: '2FA token must be 6 characters long',
              },
              minLength: {
                value: 6,
                message: '2FA token must be 6 characters long',
              },
              setValueAs: value => formatCode(value),
            })}
            onChange={handleFormatCode} //111 111
            fullWidth
            error={Boolean(errors?.token)}
            helperText={get(
              errors,
              'token.message',
              <FormattedMessage
                defaultMessage="Please enter the code from your {channel}"
                values={{ channel: get2FADevice(type2fa) }}
              />,
            )}
            InputProps={{
              startAdornment: (
                <InputAdornment position="start">
                  <VpnKey color="primary" />
                </InputAdornment>
              ),
            }}
          />

Inside the text field are used the following scripts to format the input

const handleFormatCode = event => {
    console.log('HERE');
    event.target.value = formatPastedCode(event.target.value);
  };

export const formatCode = (value = '', oldValue = '') => {
  const digits = value.replace(/[^\d]/g, '').substring(0, 6);
  const len = digits.length;
  return (value.length > oldValue.length && len >= 3) ||
    (value.length < oldValue.length && len > 3)
    ? `${digits.substr(0, 3)} ${digits.substr(3)}`
    : digits;
};

export const formatPastedCode = (value) => {
  const digits = value.replace(/[^\d]/g, '').substring(0, 6);
  const normalizeDigits = trimWhitespace(digits);
  return normalizeDigits; // 111 222
}

The above scripts serve to format the code to the right format



Solution 1:[1]

I found a solution after many hours of tries. I had to add a custom validation and I added a method using the setValue of useForm

The code of the method added on the onChange

const { register, handleSubmit, setValue, setError, errors } = useForm();

const handleFormatCode = event => {
            setValue('token', formatCode(event.target.value), { shouldValidate: true });
      };

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Jakub