REGEX patterns in LWC


Data is the fuel of any software/application implementation. It reflects the quality benchmarks of a business. Validation of data hence becomes super important. Apart from the making fields required, at times it is also significant to validate if the data arrives in a standardized format. REGEX (Regular Expression Pattern) based data validation becomes helpful here. While JavaScript natively supports REGEX matching using match function, Salesforce’s lightning-input (LWC base component) supports this REGEX validations inbuilt for email, password, search, tel, text, and URL type fields via predefined attributes.

Let’s see how this works with an example:

  1. Get the correct REGEX pattern for validation: Consider a scenario where you want users to submit valid email address. You can learn, generate and validate your own expression as needed with tools like:
  2. Apply the REGEX pattern to the lightning-input component instance using ‘pattern‘ attribute.
  3. Specify a message to be shown to users for if the data entered doesn’t match the specified pattern using the ‘message-when-pattern-mismatch‘ attribute.
  4. Here is how our Email validation lightning-input field should look like (Note: The pattern can be generated as per specific business needs, below is a simple email validation pattern):

Here is a small demonstration

💡Need a clean JSON beautifier? Try THIS


Leave a Reply

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