August 25, 2020

Dynamic Field required and error message in Salesforce LWC

Sample Code:

HTML:

<template>

    <div class="slds-theme--default slds-p-around_large">

        <lightning-input type="toggle" label="Basic option" name="toggle" onchange={onHandleValueChange}></lightning-input><br/><br/>
        <lightning-input type="text" label="Enter some text" name="text" required={requiredBool}  class="inputText"></lightning-input>

    </div>
  
</template>

JavaScript:

import { LightningElement } from "lwc";

export default class Sample extends LightningElement {

    requiredBool = false;
    showBool = true;

    onHandleValueChange( event ) {

        let selectedVal = event.detail.checked;
        console.log( "Event is " + JSON.stringify( event.detail ) );
        console.log( "Selected Val is " + selectedVal );
        if ( selectedVal === true ) {

            this.requiredBool = true;
            let inputText = this.template.querySelector( ".inputText" );
            inputText.setCustomValidity( "This field is required/mandatory" );
            inputText.reportValidity();

        }
        else {

            let inputText = this.template.querySelector( ".inputText" );
            let tempBool = false;
            if ( !inputText.value ) {
                /* Setting value to Temp to avoid Value Missing error message */
                inputText.value = "Temp";
                tempBool = true;
            }
            inputText.setCustomValidity( "" );
            inputText.reportValidity();
            this.requiredBool = false;
            if ( tempBool )
                inputText.value = undefined;

        }

    }

}

Output:

 


No comments:

Post a Comment