Lightning

LWC: Lightning-Combobox required field validation on submit button

When working with custom Lightning-combobox in LWC most of the time you will face problems making combo box a required field. When using a Lightning-record-edit-form, you usually use lightning-input-field tag and it takes care of all the FLS (Field Level Security) and irrespective of field type it handles every type of field. However, there will be scenarios where lightning-input-field may not be suitable and end up using a custom tag. For instance, a custom lookup field or multi select custom lookup field or a custom record type selection combo box. You end up using a custom solution for these.

Problem with Lightning-record-edit-form is on submit it will check FLS and required field validations only for fields with lightning-input-field tags. But what about custom fields that are in place.

Here in this blog, we will see how we can check validations of lightning-combobox and handle the same before submitting the form.

Component’s HTML page

<template>
    <lightning-record-edit-form 
        data-id="contact_Form" 
        onsuccess={handle_Record_Success}
        onsubmit={handle_Record_Submit} 
        onerror={handle_Record_Error} 
        onkeypress={handle_key}
        object-api-name="Contact" 
        record-id={contactId} >

        <div class="slds-grid slds-wrap slds-theme_default">
            
            <div class="slds-col slds-size_1-of-1 slds-large-size_6-of-12 slds-p-horizontal_small">
                <lightning-input-field field-name="FirstName" > </lightning-input-field>
            </div>
            <div class="slds-col slds-size_1-of-1 slds-large-size_6-of-12 slds-p-horizontal_small">
                <lightning-input-field field-name="LastName" > </lightning-input-field>
            </div>
            <div class="slds-col slds-size_1-of-1 slds-large-size_6-of-12 slds-p-horizontal_small">
                <!-- <div class="slds-form-element">
                    <label class="slds-form-element__label">Country</label>
                    <div class="slds-form-element__control">
                        <div class="slds-select_container">
                            <select class="slds-select" required>
                                <option value="">Please select</option>
                                <option class="uiInputSelectOption" value="United Kingdon" >United Kingdon</option>
                                <option class="uiInputSelectOption" value="United States" >United States</option>
                                <option class="uiInputSelectOption" value="India" >India</option>
                            </select>
                        </div>
                    </div>
                </div> -->

                <lightning-combobox
                    name="Country"
                    label="Country"
                    value={value}
                    placeholder="Select Country"
                    options={options}
                    required="true"
                    onchange={handle_Country_Change} ></lightning-combobox>
            </div>
            <div class="slds-col slds-size_1-of-1 slds-large-size_6-of-12 slds-p-horizontal_small">
                <lightning-input-field field-name="Email" > </lightning-input-field>
            </div>
            <div class="slds-col slds-size_1-of-1 slds-large-size_6-of-12 slds-p-horizontal_small">
                <lightning-input-field field-name="Phone" > </lightning-input-field>
            </div>
            <div class="slds-col slds-size_1-of-1 slds-large-size_6-of-12 slds-p-horizontal_small">
                <lightning-input-field field-name="MobilePhone" > </lightning-input-field>
            </div>

            <div class="slds-col slds-size_1-of-1 slds-p-horizontal_small">
                <lightning-button type="submit" variant="neutral" label="Submit" title="Submit" onclick={handle_Submit_Click}></lightning-button>
            </div>
        </div>
    </lightning-record-edit-form>
</template>

You have to handle on lightning-record-edit-form’s “onsubmit” method. Here in this example handle_Record_Submit is the method.

Here you can see lightning-combobox is set required as true

                   <lightning-combobox
                    name="Country"
                    label="Country"
                    value={value}
                    placeholder="Select Country"
                    options={options}
                    required="true"
                    onchange={handle_Country_Change} ></lightning-combobox>

JS field.

import { LightningElement } from 'lwc';

import { ShowToastEvent } from 'lightning/platformShowToastEvent';

export default class Test_Component extends LightningElement {

    value = '';

    get options() {
        return [
            { label: 'United Kingdom', value: 'United Kingdom' },
            { label: 'United States', value: 'United States' },
            { label: 'India', value: 'India' },
        ];
    }
    
    handle_Country_Change(event){
        var selected_Value = event.detail.value;
        console.log('-=-=: '+selected_Value);
    }

    handle_Record_Submit(event){
        event.preventDefault();
        const fields = event.detail.fields;

        // Validating a lightning-combobox field 
        // you can change it to lightning-input or lightning-rick-text or lightnig-name or lightinig-address etc.
        // here in this example lightining-combobox is a required field.
        // since lightning-record-edit-form only validates lightning-input-field tag.
        // to validate lightning-combobox (all lightning-combobox) tag in the form.

        const All_Compobox_Valid = [...this.template.querySelectorAll('lightning-combobox')]
            .reduce((validSoFar, input_Field_Reference) => {
                input_Field_Reference.reportValidity();
                return validSoFar && input_Field_Reference.checkValidity();
            }, true);

        if(All_Compobox_Valid){
            // This means all required fields or other validations on combobox fields are entered correctly.
            // you can assign country valie to any field using the fields constant that is assigned above.
            // once assighed submit the lightning-record-edit-form with fields.
            this.template.querySelector('lightning-record-edit-form').submit(fields);
        }
        else{
            // show toast error message if required
            /*
            const event = new ShowToastEvent({
                title : 'Error',
                message : 'Please select country.',
                variant : 'error'
            });
            this.dispatchEvent(event);
            */
        }
    }

    handle_Record_Success(event){
        console.log('Record Id: '+event.detail.id);
    }
    
}

You need to handle the validation rule on any type of tag. just change the type of tag in below code.

const All_Compobox_Valid = [...this.template.querySelectorAll('lightning-combobox')]
            .reduce((validSoFar, input_Field_Reference) => {
                input_Field_Reference.reportValidity();
                return validSoFar && input_Field_Reference.checkValidity();
            }, true);

        if(All_Compobox_Valid){
            // This means all required fields or other validations on combobox fields are entered correctly.
            // you can assign country valie to any field using the fields constant that is assigned above.
            // once assighed submit the lightning-record-edit-form with fields.
            this.template.querySelector('lightning-record-edit-form').submit(fields);
        }
        else{
          
        }

Just change lightning-combobox to any other tag.

input_Field_Reference is a reference to all combobox fields that are in form. It checks for validity using reportValidity(); one by one and return true or false.

OUTPUT:

Fires validation error on submit

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s