[SalesForce] onChange event is not fired for lightning:input type=”datetime” when clear Time field

I have the following component:

Example.cmp

    <lightning:input
        aura:id="field"
        type="datetime"
        name="datetimeInput"
        label="Set up a date/time"
        value="{! v.scheduleDatetime }"
        required="true"
        onchange="{! c.onChange }"
    />

</aura:component>

ExampleController.js

onChange: function(component, event, helper) {
    console.log("onChange", event.getSource().get("v.value"));
    const target = event.getSource();
}

enter image description here

When I select a date, the time part is populated automatically. I see the console log for the onchange event:

onChange 2019-05-28T22:30:00.000Z

It also works when I change time value. So far so good.

enter image description here

But when I clear the time part, the onchange event is not fired. And the value of this component remains 2019-05-28T22:30:00.000Z. This is awkward because I expect the value to become either 2019-05-28T00:00:00.000 or null (which is better).

enter image description here

I need to be able to catch onchange events for such cases, or at least get the correct value when run my custom validation. Now when I access component value during validation component.find("field").get("v.value"), I see the last valid datetime value, not the current one with the time part cleared. This means that users can submit the form when the Time is empty, whereas it's not actually empty… This is confusing.

Is there a workaround?

Best Answer

If I have understood your problem correctly, I think you make use of the validity property as described in the documentation. So instead of checking the null values, you can directly check if the field is valid using the below code.

var validity = component.find("field").get("v.validity");
console.log("Is it valid? ", validity.valid); //returns true
Related Topic