Lightning Web Components – Fixing Issue with Replacing First Invalid Character

lightning-web-componentsregular-expressions

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

Best Answer

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.