0

How to check if date type lightning input is empty? I tried using a property say "dateProperty" which contains value of date input field and in JS used condition like, if (!empty(dateProperty)) but got error like [empty is not defined].Then i tried something like if (dateProperty!= undefined) also (dateProperty!= null) but got error like [dateProperty is not defined].Not sure how to go about it or why am i getting UNDEFINED error?

2
  • Can you provide more code to show what you're doing? Preferably build an example in the playground – gNerb Jun 18 '20 at 15:38
  • 1
    I tried everything but finally realized the issue is i was not using "This." in front of property name. – Return0 Jun 18 '20 at 16:06
1

You simply check the value of the input field, the same as you'd do for most other types as well.

Playground.

import { LightningElement } from 'lwc';

export default class App extends LightningElement {
    dateCheck = 'Not Checked';
    check(event) {
        this.dateCheck = this.template.querySelector('lightning-input').value? 'Populated': 'Not Populated';
    }
}

<template>
    <lightning-input type="date" label="Demo">
    </lightning-input>
    <lightning-button label="Check" onclick={check}>
    </lightning-button>
    Date Check: {dateCheck}
</template>
1

SFDC Fox's answer will work but I'd like to propose an alternate approach (playground).

HTML:

<template>
    <div class="app slds-p-around_x-large">
        <lightning-input 
            type="date" 
            label="Demo" 
            onchange={handleDateChange}
        ></lightning-input>
        <lightning-button 
            label="Do Action" 
            onclick={doAction} 
        ></lightning-button>
    </div>
</template>

JS

import { LightningElement, track } from 'lwc';

export default class App extends LightningElement {
    @track dateValue;

    handleDateChange(event) {
        this.dateValue = event.detail.value;
    }

    doAction(event) {
        if (this.dateValue) {
            console.log('win');
        } else {
            console.log('lose');
        }
    }
}

Some advantages to this approach:

  • Just in time Field Level validations
  • Dependent picklists
  • Etc.

Here is a full component that was developed with this approach.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.