function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
AichaSFAichaSF 

lighning Component - Required Field Validation

Hello everyone, 
Has someone exemple of validate required fields in lightning component?
Thank you.
Raj VakatiRaj Vakati
You can refer this link 
https://developer.salesforce.com/docs/atlas.en-us.lightning.meta/lightning/js_validate_fields.htm
Enter a number: <ui:inputNumber aura:id="inputCmp"/> <br/>
    <lightning:button label="Submit" onclick="{!c.doAction}"/>
 
/*errorHandlingController.js*/
{
    doAction : function(component) {
        var inputCmp = component.find("inputCmp");
        var value = inputCmp.get("v.value");

        // Is input numeric?
        if (isNaN(value)) {
            // Set error
            inputCmp.set("v.errors", [{message:"Input not a number: " + value}]);
        } else {
            // Clear error
            inputCmp.set("v.errors", null);
        }
    }
}

 
Balagopal GBalagopal G

Hi

you can also validate based on different events

eg:keydown,kepup,button events,onblur etc.

for example:-

<input aura:id="min" id="min" class=" slds-input"  onkeydown="{!c.numberCheck}" type="text" name="input1" placeholder="min" label="Enter a Min value"  />

onkeydown="{!c.numberCheck}"

numberCheck: function(component, event, helper){         
         
        if((event.keyCode>=48 && event.keyCode<=57 ) || event.keyCode==08){
            
        }else{
            event.preventDefault();
        } 
    }

In the above , i am restricting the user to input only what i require.

similarly the same method or modified on can be used in all the events to have validation in lightning component level.