Making Conditional Required In Lightning Web Component

Lets discuss here how to make the field as required in conditionally in lightning web components. In this example, we will be making the field as required conditionally if the selected value is hot.

 

Create a lightning web component using the following SFDX command

sfdx force:lightning:component:create --type lwc --componentname conditionalrequired --outputdir force-app\main\default\lwc

 

Here is the conditionalrequired.html code. In this code, we will be showing the picklist values and based on the selected picklist value we are making the conditional required.

<template>
    <lightning-card title="Conditional Required" icon-name="standard:calibration">
        <div class="slds-form-element">
            <template if:true={ratings.data}>
                <div class="slds-combobox_container slds-size_small">
                    <select onchange={handleOnChange}>
                        <template for:each={ratings.data.values} for:item="item">
                            <option key={item.label}>{item.label}</option>
                        </template>
                    </select>
                </div>
            </template>
            <lightning-input type="text" name="inputtext" label="Enter Input" value="text" required={makerequired}></lightning-input>
            <template if:true={ratings.error}>
                {errors}
            </template>
        </div>
    </lightning-card>
</template>

 

 

Use the below conditionalrequired.js code

import {
    LightningElement,
    wire,
    api
} from 'lwc';
import {
    getPicklistValues
} from 'lightning/uiObjectInfoApi';
import RATING from '@salesforce/schema/Account.Rating';
export default class Conditionalrequired extends LightningElement {
    @api selectVal;
    @wire(getPicklistValues, {
        recordTypeId: '012000000000000AAA',

        fieldApiName: RATING
    })
    ratings;



    handleOnChange(event) {
        this.selectVal = event.target.value;
    }
    get makerequired() {
        if (this.selectVal === "Hot") {
            return true;
        } else {
            return false;
        }
        return ;
    }
}

 

use this conditionalrequired.js-meta.xml code to configure this component to app builder

 

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata" fqn="ConditionalRendering">
    <apiVersion>45.0</apiVersion>
    <isExposed>true</isExposed>
    <targets>
        <target>lightning__RecordPage</target>
    </targets>
</LightningComponentBundle>

 

Push the changes to scratch and add them to page layout.

 

 sfdx force:source:push --forceoverwrite

 

You can able to see the output as shown below.