I tried following the tutorial here https://www.sfdcstop.com/2018/03/salesforce-lightning-tutorial-part-5.html but got stuck as below.
a.cmp
...
<td>
<lightning:input aura:id="formFieldToValidate"
messageWhenValueMissing="Either Nationality ID Number OR Passport Number is to be filled"
name="nationalid"
value="{!item.nth.National_ID_Number__c}"/>
</td>
<td>
<lightning:input aura:id="formFieldToValidate"
messageWhenValueMissing="Either Nationality ID Number OR Passport Number is to be filled"
name="passportnumber"
value="{!item.nth.Passport_Number__c}"/>
</td>
...
aController.js
({
validate : function(component,event){
// Getting all fields and iterate them to check for validity
var allValid = component.find('formFieldToValidate').reduce(function (validSoFar, inputCmp) {
// Show help message if single field is invalid
inputCmp.showHelpMessageIfInvalid();
// Get the name of each field
var name = inputCmp.get('v.name');
var passportValue;
var nationalIdValue;
if(name=='nationalid') {
nationalIdValue = inputCmp.get('v.value');
}
if(name=='passportnumber') {
passportValue = inputCmp.get('v.value');
}
if(nationalIdValue == '' && passportValue == '') {
// Focus on that field to make custom validation work
inputCmp.focus();
// Setting the custom validation
inputCmp.set('v.validity', {valid:false, badInput :true});
}
// Returning the final result of validations
return validSoFar && inputCmp.get('v.validity').valid;
}, true);
// Returning Validate contact result in boolean
return allValid;
}
When I tried not filling both fields and then click "Save", nothing happens and no error message is prompted. How do I get this to work?