Background
I have a lightning component with a lightning:recordEditForm
for creating new Opportunity
records.
The lightning:recordEditForm
contains many lightning:inputField
's
I would like to perform basic required field validation on the form, using code like this:
let isValid = true;
let fields = cmp.find("requiredField"); // gets all required fields
for (var i = 0; i < fields.length; i++) {
if (fields[i] != null) {
if (fields[i].get('v.validity').valid == false) {
fields[i].showHelpMessageIfInvalid();
isValid = false;
}
}
}
But I am unable to access property validity
/ valid
on the lightning:inputField
And I am unable to call the showHelpMessageIfInvalid()
method on the lightning:inputField
Questions
- How should I approach form validation using
lightning:recordEditForm
- How can I get each field to display the red border if the field is not valid?
Best Answer
You are not able to use
validity
on lightning:inputField because the attribute is not supported on this component, instead its an attribute for lighting:input.For validating
lightning:inputField
withlightning:recordEditForm
, you can refer to this answer which provides a perspective as how you can validate values entered on the component.For the error scenarios, you can utilize the CSS that's available for the purpose. You can refer to more on this on SLDS documentation for the component from where it inherits the styling.