Lightning Base component <lightning:input type="text" /> Input text validation example
Lightning Base component <lightning:input type="text" /> Input text validation example
Capturing component markup UI values in component JS controller.
Doing some validation on input text entered and displaying error message.
Application markup
InputCompValidation.app
<aura:application extends="force:slds">
<c:InputValidation />
</aura:application>
Component Markup
InputValidation.cmp
<aura:component implements="flexipage:availableForAllPageTypes" access="global" >
<aura:attribute name="firstName" type="String" />
<aura:attribute name="lastName" type="String" />
<aura:attribute name="midName" type="String" />
<br/>
<br/>
<lightning:input aura:id="inputFirstName" type="text" label="First Name" value="{!v.firstName}" />
<br/>
<lightning:input aura:id="inputMidName" type="text" label="Middle Name" value="{!v.midName}" />
<br/>
<lightning:input aura:id="inputLastName" type="text" label="Last Name" value = "{!v.lastName}" />
<br/>
<br/>
<lightning:button aura:id="buttonApply" label="Apply" variant="brand" onclick="{!c.check}"/>
</aura:component>
Client side JS Controller
InputValidationController.js
({
check : function(component, event, helper) {
var inputFieldFirstName = component.find("inputFirstName");
if(inputFieldFirstName != null) {
var fname = inputFieldFirstName.get("v.value");
console.log('Value of First Name is ' + fname);
} else {
console.log('inputField for first name is null');
}
var inputFieldMidName = component.find("inputMidName");
if(inputFieldMidName != null) {
var mname = inputFieldMidName.get("v.value");
console.log('Value of Middle Name is ' + mname);
} else {
console.log('inputField for mid name is null');
}
var inputFieldLastName = component.find("inputLastName");
if(inputFieldLastName != null) {
var lname = inputFieldLastName.get("v.value");
console.log('Value of Last Name is ' + lname);
} else {
console.log('inputField for last name is null');
}
console.log(inputFieldFirstName.get('v.validity').valid);
if($A.util.isEmpty(fname)) {
inputFieldFirstName.setCustomValidity("You must enter a value for First Name.");
inputFieldFirstName.reportValidity();
} else {
inputFieldFirstName.setCustomValidity("");
inputFieldFirstName.reportValidity();
console.log(inputFieldFirstName.get('v.validity').valid);
}
console.log(inputFieldLastName.get('v.validity').valid);
if ($A.util.isEmpty(lname)) {
inputFieldLastName.setCustomValidity("You must enter a value for Last Name.");
inputFieldLastName.reportValidity();
} else {
inputFieldLastName.setCustomValidity("");
inputFieldLastName.reportValidity();
console.log(inputFieldLastName.get('v.validity').valid);
}
}
})