Salesforce Cookies #13

      No Comments on Salesforce Cookies #13

How to validate fields in lightning components ( Form Validation in Lightning Component )

Some lightning components come with inbuilt validation and you need to trigger the validation in your client-side controller. Following components provide inbuilt validation support.

  • lightning:input
  • lightning:select
  • lightning:textarea
  • ui:input*

lightning:input is more powerful when it comes to the validation as it honors the HTML5 validations too like setting the min and max limit on an element.

For the components which are part of the “ui” namespace like ui:input, you need to check it manually in the client-side code. These components have a property which is “errors” and you can set a list of errors to that property which will be displayed alongside the ui:input component.

How to add an error to ui:input

Adding an error to a ui:input is very simple. You just need to check whether it’s having the clean data or not and then add the error to the component.

var emailCmp = component.find("email");
var email = inputCmp.get("v.value");
var filter = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
// If it's blank
if ( email ) {
 // Set error
 emailCmp.set("v.errors", [{message:"Email is required"}]);
else if ( !filter.test( email ) ) {
    emailCmp.set("v.errors", [{message:"Email is not valid"}]);


I hope it explains a basic approach towards the validation. Please feel free to comment as it really important for the improvements.



About Naval Sharma

I am certified Salesforce Developer with Sales and Service cloud certifications. I am a true believer in #GivingBack principle and a Salesforce enthusiast. I am working as a member of our #SalesforceOhana to learn and help other fellow Trailblazers of the community to grow and learn. "I'm a true believer in karma. You get what you give, whether it's bad or good."

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.