In this article you will learn how you can restrict user to select Past Dates or Future Dates using Date Picker in Lightning Component.
Step : 1
Download below JQuery UI & Plugin
1. JQuery UI
2. Plugin
Step : 2
Upload JQuery UI & Plugin as static resource in your org. In below example I am uploading JQuery UI zip file as DateJQuery and Plugin js file as jqueryminjs.
Just make sure the cache control is public while creating static resources.
Step : 3
First we will try script to block past dates. Please create component and controller as shown below :
Component
1 2 3 4 5 6 7 8 9 10 | <aura:component implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickAction" access="global" > <ltng:require styles="{! $Resource.DateJQuery + '/jquery-ui-1.12.1/jquery-ui.min.css'}" scripts="{!join(',', $Resource.jqueryminjs , $Resource.DateJQuery + '/jquery-ui-1.12.1/jquery-ui.min.js') }" afterScriptsLoaded="{!c.runScripts}"/> <input type="text" class="slds-input" id="mydatepicker" /> <lightning:button variant="brand" onclick="{!c.getDate}" label="Get Date"/> </aura:component> |
Controller
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | ({ runScripts : function(component, event, helper) { $(document).ready(function(){ $( "#mydatepicker" ).datepicker({ beforeShowDay: function(date) { var today = new Date(); if(date > today){ return [true]; } else{ return [false]; } }, }); }); }, getDate : function(component,event,helper){ var oDate = $('#mydatepicker').val(); alert(oDate); } }) |
The above component will restrict user to select past dates from the date picker. To restrict user to select future date from date picker you just have to edit the line number 7 from the controller.
Just update it to if(date < today){ and you are good to go !
Output
5 Comments
What if i want to resrict only three dates in future along with past dates
ReplyDeleteHave you tried it by specifying the condition on line number 7 JS ?
DeleteHi,
ReplyDeleteI tried above with all steps but for some reason its not working for me.
Could you please help me with this? Its not showing up calendar to pick date please let me know what I am doing wrong.
How to achieve same thing in LWC?
ReplyDeleteHello @Vishal , were you able to achieve this functionality using LWC?
Delete