lightning:input Date Field validation

user10490801 picture user10490801 · Oct 11, 2018 · Viewed 7.1k times · Source

I am trying to use Standard Date picker using below component but however I want to display custom error message when the enterted date is not in the speciied min & max range. But I am not able to achieve it as I could see the standard error message. I implemented the same by referring to : https://developer.salesforce.com/docs/component-library/bundle/lightning:input/example and in this link I can see that the custom error messages can be shown. But nothing worked for me can anyone please help. https://developer.salesforce.com/docs/component-library/bundle/lightning:input/documentation

<lightning:input aura:id="field
                     type="date" 
                     name="MyDatefield" 
                     label="MyDateField" 
                     value="2017-09-07" 
                     min="2017-09-05" 
                     messageWhenRangeUnderflow="Select correct date range1"
                     max="2017-09-22" 
                     messageWhenRangeOverflow="Select correct date range2"
                     onchange="{!c.checkValidity }"
</aura:component>

Answer

TheTimeKeeper picture TheTimeKeeper · Dec 7, 2018

This was asked 1 month back but sharing the answer if anybody else runs across this. Use lightning's setCustomValidity() and reportValidity() methods.

Component:

    <aura:component >
    <lightning:input aura:id="field"
                     type="date" 
                     name="MyDatefield" 
                     label="MyDateField" 
                     value="2017-09-07" 
                     min="2017-09-05" 
                     max="2017-09-22" 
                     onblur ="{!c.checkValidity }"
             />
</aura:component>

Controller:

({
    checkValidity : function(component, event, helper) {
        var inputCmp = component.find("field");
        inputCmp.setCustomValidity(""); //reset error
        var value = inputCmp.get("v.value");
        console.log('value: '+value);
        var lowerRange =  new Date("2017/09/05"); 
        var higherRange =  new Date("2017/09/22"); 
        if(!inputCmp.checkValidity()){
            if(Date.parse(value)){
                if (Date.parse(value) < lowerRange) {
                    inputCmp.setCustomValidity("Select correct date range1");
                }else if (Date.parse(value) > higherRange){
                    inputCmp.setCustomValidity("Select correct date range2"); 
                }
            }else{
                inputCmp.setCustomValidity("Invalid value");
            }
        }
        inputCmp.reportValidity();
    }
})