0

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' />
1
  • I've never done this, but seems like you might want to look into creating a second const to store the actual value but then you just need a way to prevent the masked value from overwriting the unmasked value Commented Jul 29, 2020 at 22:34

1 Answer 1

1

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)
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.