0

I'm new with all the LWC topic. But for now I'm having issues with some regex. To Begin with I have my own LWC created with a few fields some of them are type number such this one:

<lightning-input label="CCV" type="number" value={valueCvv} onchange={handleCvvChange} id="card-ccv" maxlength="3"></lightning-input>

From what I'm trying to do in this case CCV is for the input only accept numbers (0-9). But for now is accepting them but also this characters ´ + , . -. Here is the event:

 handleCvvChange(event){
    this.valueCvv = event.target.value;    
    event.detail.value = event.detail.value.replace(/^([0-9])*$/,'');
}

Thanks in advance!

0
0

change the handleCvv method to this:

In template change `onchange` to `onkeypress`

handleCvvChange(event) {
    if (event.key.length === 1 && /\D/.test(event.key)) {
        event.preventDefault();
    } else {
        this.valueCvv = event.target.value;
    }
}

what this does is we replace all non digit character with the value you specified in the second parameter of .replace method and reassign it back to valueCvv property

4
  • Thanks for your answer, I changed it. But still letting me to add those characters. – Pablo Calderón Jan 14 at 18:47
  • Hi pablo. I updated my answer. Can you please try again – drm Jan 14 at 19:09
  • To see it in action: webcomponents.dev/edit/3Qr43KJ1tAi8zPo0IJw6 – drm Jan 14 at 19:12
  • Thanks again for your answer!. couldn't find an example by using onkeypress thanks for it. I have found another solution. Would you add it? it works with onchange I'll mark it as solved. handleCvvChange(event){ event.target.value = event.target.value.replace(/[^0-9]/g,''); } – Pablo Calderón Jan 14 at 19:29

Not the answer you're looking for? Browse other questions tagged or ask your own question.