Lightning input components allow you to create input for the form elements. They have built-in validations, based on the type of field, and can be used with various data types. To learn more about Lightning: input, refer to the standard component library at https://developer.Salesforce.com/docs/component-library/bundle/Lightning:input/example.
The following snippet shows a working example of the code for the Lightning:input component. The component markup creates a simple form for lead capture. Notice that we have made all of the fields mandatory by using the required attribute on lighnting:input:
<aura:component access="global" >
<aura:attribute name="lastName" type="String"/>
<aura:attribute name="email" type="String" />
<aura:attribute name="company" type="String" />
<aura:attribute name="phone" type="String" />
<aura:handler name="init" value="{!this}" action="{!c.onInit}"/>
<aura:if isTrue="{!v.isSpinner}">
<Lightning:spinner variant="brand" size="small" />
</aura:if>
<Lightning:messages />
<div class="slds-grid slds-gutters">
<div class="slds-col slds-size_1-of-2">
<Lightning:input aura:id="field" name="LastName" label="LastName" value="{!v.lastName}" required="true"/>
<Lightning:input aura:id="field" name="Email" label="Email" type="email" value="{!v.email}" required="true"/>
<Lightning:input aura:id="field" name="Phone" type="tel" label="Phone" value="{!v.phone}" required="true"/>
<Lightning:input aura:id="field" name="Company" type="text" label="Company" value="{!v.company}" required="true"/>
</div>
</div>
<div class="wrapper">
<Lightning:button variant="brand" class="slds-m-top_small" onclick="{!c.handleSubmit}" label="Let's Talk" />
</div>
</aura:component>
The controller code shows how to add validation checks using the out-of-the-box attributes provided and the reduce JavaScript function:
({
handleSubmit : function(component, event, helper) {
var allValid = component.find('field').reduce(function (validSoFar, inputCmp) {
inputCmp.showHelpMessageIfInvalid();
return validSoFar && inputCmp.get('v.validity').valid;
}, true);
if (allValid) {
component.set("v.isSpinner",true);
//call apex here
} else {
component.set("v.isSpinner",false);
var toastEvent = $A.get("e.force:showToast");
toastEvent.setParams({
"title": 'Error',
"message": 'Please update the invalid form entries and try again.',
"type": "error",
"mode": "sticky"
});
toastEvent.fire();
}
},
})