Reputation: 522
I'm trying to make an input mask without using jquery. Only using the states of reactjs.
But, whenever he formats the field, I can't erase what was written on it. I will put my code below, in case you have any other way to do this I also accept.
The mask is to be in the format 9999999-9
My code:
const [accountRegex, setAccountRegex] = React.useState('');
function handleAccountRegex(event) {
setAccountRegex(event.target.value)
if (accountRegex.length === 8) {
setAccountRegex(accountRegex.replace(/(\d{7})(\d{1})/g, "$1-$2"))
}
}
<Input name="account" label="Conta" required={true} onChange={handleAccountRegex} value={accountRegex} maxLength='8' />
Upvotes: 0
Views: 239
Reputation: 4139
I've made some changes:
function handleAccountRegex(event) {
// first make sure input doesn't contain the "-" character in it
// because it will mess up the "backspace" key functionality
let val = event.target.value.replace("-", "")
// if input value is 8 digits mask it
if (val.length === 8) {
setAccountRegex(val.replace(/(\d{7})(\d{1})/g, "$1-$2"))
}
// else just store the changes
else setAccountRegex(val)
}
Upvotes: 1