Show custom error on lightning:input

I was trying if we can validate input in javascript and then post errors on latest lightning:input. But i think it doesn’t support such use case.

pattern attribute is there but it cant work when i/p is based on other fields.

The requirement I am trying to achieve is that phone number without spaces should be 11 digits.


          <lightning:input type="tel" label="Telephone"
             name="tel" value="{!v.applicant1.Phone__c}" pattern="^[0-9_ ]*$"
             messageWhenPatternMismatch="Phone number is not valid"
             messageWhenBadInput='Phone number should be 11 chars max'


checkValidityOfphone : function(component, event, helper) {
  console.log('checkValidityOfphone called');
  var inp = event.getSource();
  var val=inp.get('v.value');
  val=val.replace(/ /g,'');
    inp.set("v.errors", [{message:"Input not a number: " + val}]);
    console.log('Error Set called');   
    //  inp.get('v.validity').valid=false;

According to the given doc, lightning:input does support client side validations.


This is a bit of an old question now, but I’ve discovered another way which seems pretty legit. The validity attribute of lightning:input is not just for reading the validity, you can also set it. So, write the component like this:

<aura:handler name="change" value="{!v.value}" action="{!c.valueChangeValidation}"/>

<lightning:input aura:id="inputField" 
                 type="text" value="{!v.value}" 
                 label="Enter foo" 
                 messageWhenBadInput="You must say foo" />

And then the controller like this:

valueChangeValidation : function(component, event, helper) {
    var inputField = component.find('inputField');
    var value = inputField.get('v.value');
    if(value != 'foo') {
        inputField.set('v.validity', {valid:false, badInput :true});


Then, you can write whatever logic you want in that handler method and the result is shown in the normal Lightning way.

Source : Link , Question Author : Pranay Jaiswal , Answer Author : Pranay Jaiswal

Leave a Comment