How to Validate forms built with Lightning Components

Learn how to validate lightning components forms easily.

I recently had a requirement to create a basic lightning component to capture form inputs. I previously had a not so good experience with building custom validation with Lightning components back in Summer17 when lightning was pretty new. I was using force:inputField and also used lightning:inputField.

Past few years it has become more efficient and easier with just the lightning:input field and default HTML5 APIs.

I have a simple bank form that captures and validates the form as such and when submitted validates the required fields.

Form

For the Bank Account Name input field specify the required attribute as true and check the validity of the field.

I use reportValidity to display the error message in the input field

And for the Bank Account Number input field aside from setting the field as true, I also specified a regular expression pattern. And then used the setCustomValidity function to display a custom error message.

And that folks, is how easy to validate the input form. Hit the comments below if you need help building your validation.

One thought on “How to Validate forms built with Lightning Components

Leave a Reply

Your email address will not be published. Required fields are marked *