0

I need to put a validation on lightning input field date. It is a date of birth field and it should not accept date beyond system.today(). Basically the validation will be date_Of_birth > Today() , then there should an error message.

The error message should display beside the lightning input field.

Is it possible? can anyone help?

2 Answers 2

1

You can use the built-in validation logic of the lightning:input component.

There is a max attribute on the lightning:input component in which you need to provide the max date value in the YYYY-MM-DD format - documenation. lightning:input - date value validation

To get today's date you will need to use the JS Controller - on init of your component call function to prepare today's date in the correct format:

new Date().toISOString().split('T')[0]

Let's store the prepared date value in the todaysDate aura attribute (remember to declare such attribute in your .cmp file):

component.set('v.todaysDate', new Date().toISOString().split('T')[0]);

Now you can finally use the todaysDate aura attribute in the max attribute of the lightning:input:

max="{!v.todaysDate}"

DEMO

Day Of Birth - max value validation

FINAL FILES

DayOfBirthInputValidation.cmp

<aura:component implements="flexipage:availableForAllPageTypes" access="global">
    
    <aura:attribute name="todaysDate" type="String"/>
    
    <aura:handler name="init" value="{!this}" action="{!c.onInit}"/>
    
    <lightning:card>
        <div class="slds-box slds-theme_shade slds-theme_alert-texture slds-m-around_medium">
            Today is: <b>{!v.todaysDate}</b>
        </div>
        <lightning:input
                         label="Day Of Birth"
                         type="date"
                         dateStyle="short"
                         max="{!v.todaysDate}"
                         class="slds-p-around_medium"
        />
    </lightning:card>
</aura:component>

DayOfBirthInputValidationController.js

({
    onInit: function(component, event, helper) {
        component.set('v.todaysDate', new Date().toISOString().split('T')[0]);
    }
});
0

I think you should look at this answer.

In the controller replace the dateRange variables with the current date:

var today = new Date(); //returns date time. 

If you need Time to be 00:00:00 then set it for today before comparing:

today.setHours(0, 0, 0, 0);

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .