'How to remove in NextJS/React white spaces and non integer charcters when copy pasting a 2fa code inside a texfield input
I have a login that requires a 2FA authentication which is sent by email to the user.
The code is long 6 digits.
When a user copy-paste the code that appears as 111 111
and it triggers the validation as an example
What I need to achieve and I don't know how is that on paste, before the validation is triggered, remove what is not an integer and white space so the number is formatted as
111111
so it is 6 digits long.
So every time a user paste or just write 6 digits number but with the wrong format that should be formatted in the right way for example
Client-side input validation should allow inputs such as:
111-222 --> 111222 we remove the -
111222 --> already correct format
111 222 --> 111222 we remove the white space
11 22 33 --> 112233 we remove the white spaces
11-22-33 --> 112233 we remove all the dashes
1-2-3-4-5-6 --> 123456 we remove all the dashes
The client should be allowed to write in those formats but soon as has 6 digits they have to transform to the right format so the user can submit without caring to remove or correct any.
The only validation which will be remaining there is that a code cannot be more then 6 digits.
The code for the input field
<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),
})}
fullWidth
error={Boolean(errors?.token)}
helperText={get(
errors,
'token.message',
<FormattedMessage
defaultMessage="Please enter the code from your {channel}"
values={{ channel: get2FADevice(type2fa) }}
/>,
The format code on setValueAs
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;
};
I was trying to understand how to use the clipBoard functionalities but I have no idea as I'm new to React.
Update As for now got no answer but still, I don't know what to do having issues fix my problem. I tried to use RegEx but without a success and sharing my failure try.
The components here are from Material UI v5
I added an onChange
inside the TextField
as follows
const handleChangeValue = event => {
setCode(event.target.value.replace(/\D/g, '')); //removes every character but numerics
};
plus just inside the TextField
I added this
value={code}
onChange={handleChangeValue}
But the result is very strange
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|