1

In my LWC, I have a text input where I need to prevent the user from entering anything besides a number or a decimal point. The Javascript function I'm using does replace the invalid characters with a null string. However, if the user enters an initial minus sign, that character isn't removed until the user enters a second character.

Is there a way to immediately replace that initial minus sign immediately after it is typed?

enter image description here

enter image description here

Following is the code:

payment2.html

<template>
    
    <div class="slds-var-p-around_large slds-var-m-around_medium" style="width: 200px; background: #fff;">

        <lightning-input 
            type="number" 
            name="anotherAmount" 
            label="Another Amount" 
            variant="standard" 
            value={anotherAmount} 
            min="1"
            onchange={handleAnotherAmountChange}
            formatter="currency"
            >
        </lightning-input>

    </div>

</template>

payment2.js

import { LightningElement } from 'lwc';

    const anotherAmountStripInvalidChars = value => {
        let returnValue = value.replace(/[^0-9.]/g,'');
        return returnValue;
    }

    export default class Payment2 extends LightningElement {

    anotherAmount;

    handleAnotherAmountChange(event) {
        const value = event.detail.value;

        const xform = anotherAmountStripInvalidChars(value);
        console.log('xform:', xform);

        this.anotherAmount = xform;
    }

}

A live example: https://webcomponents.dev/edit/lCXRIYqj4Iwt88qOZzml/src/app.css?p=stories

GitHub repo: https://github.com/mikesobczak/LWC-Invalid-Chars-Issue

1
  • I'm curious as to why I was down-voted? I got an awesome response to this question, so the down-vote seems unfair. Commented Apr 18, 2022 at 18:11

1 Answer 1

2

You can filter out the hyphen in a keydown event handler.

<lightning-input type="number" name="anotherAmount" label="Another Amount" variant="standard" value={anotherAmount}
    min="1" onkeydown={checkKey} onchange={handleAnotherAmountChange} formatter="currency">
</lightning-input>

checkKey(event) {
    if(event.key.length === 1 && !event.key.match(/[0-9\.]/)) {
        event.preventDefault();
    }
}

Demo.

2
  • Brilliant! Let me know if you have a digital tip jar, so I can buy you a beer! Commented Apr 18, 2022 at 12:57
  • 1
    @MichaelSobczak You can find one on venmo under this moniker, or you can use the link on my profile. Tips are always appreciated 😁.
    – sfdcfox
    Commented Apr 18, 2022 at 13:15

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .