I am using a lightning:input
to get a date/time value in the users Locale.
If the user picks a date that is beyond today I need to prevent that value from being entered.
I am able to catch this event and set the value to null BUT the date picker still populates the date. The time is cleared.
Any ideas how to prevent the picker from entering the date?
<lightning:input type="datetime" name="end-date" onchange="{!c.endDateUpdated}" label="Enter a end date/time" aura:id="end-date"/>
Controller JS
endDateUpdated: function(component,event,helper){
var target = event.getSource();
if(!$A.util.isUndefinedOrNull(target)) {
var enteredValue = target.get("v.value");
var g = new Date();
if(Date.parse(enteredValue) > g.getTime()){
component.find("end-date").set("v.value",null);
event.preventDefault(); //Does not work
alert('Invalid Date');
}
}
}
Attempt based on answer to change to onclick
When changing the onchange
to onclick
a different issue occurs. The Date being int he future IS caught and cleared. But if the current day is picked AND the time is changed to a future time, it is NOT caught. Confirmed with onchange
both are caught. With onchange
if the time is placed in the future (with current date) then the date is cleared properly.
Results after clicking a future date:
Notice how the time is cleared but the picked date is populated. Now if the field had a valid value to begin with it will get cleared as expected.
Best Answer
Ok. Based on sanket's answer and finding that if a valid value is entered first, I have defaulted to value to the current date/time and now it works.
Basically the issue only happened if the lightning:input did not have an initial value. Once that value is set it works properly.....
Bug??
Working markup
Markup
JS