Saturday, March 16, 2019

Email Address Validation Using Dataweave Regex

Introduction

This short article is about how to use regex with Dataweave 2.0 with regard to email validation. Regex is used in Mulesoft language very wide with regard two functions, matchs(...) and match(...). It is very important to master the regular expression in order to be professional in Mulesoft integration projects. The are a lot of reference available one. Here are few:

Use Case

We expect the output of the dataweave transformation as the following depending on the validity of the email address:
[
    {
        ...
        "invalidEmail": "johndo@yahoo"
        ...
    },
    {
        ...
        "PersonEmail": "john.smith@google.com"
        ...
    },
    ...
]

Invalid Emails

The following types of emails are invalid:
  1. beginning with a dot: .gary.liu@google.com
  2. ending with a dot: gary.liu@google.com.
  3. double dots: gary.liu@google..com
  4. domain name contains underscore: gary.liu@att_rr.com
  5. domain name contains space: gayr.liu@att rr.com
  6. domain name contains and of the following: ,<>/[]
  7. no organization email: gary@google

Solution

%dw 2.0
output application/json
var regexEmail = /^[^.][a-zA-Z0-9.!#$%&’*+\/=?^_`{|}~-]+@[a-zA-Z0-9-](?!.*?\.\.)[^_ ; ,<>\/\\]+(?:\.[a-zA-Z0-9-]+)[^.]*$/
---
payload map using (email = $.email) {
 (validEmail: email) if (email matches regexEmail),
 (invalidEmail: email) if ( not  (email matches regexEmail))
}
The above dataweave script is self-explanatory. Few explanation is required if you are not very familiar with regular expression:
  1. negation: [^_;,\.] this expression means if the email domain contains underscore _ , semi-coma, etc. is not valid email
  2. simple ^ and $ represent the beginning and end of the line
  3. [a-zA-Z0-9] mean any charater A a, Bb ... Zz, or 0 to 9 digits are valid
  4. + sign means to match one for more
  5. * sign matches 0 or more
  6. ?! means not include, (?!.*?\.\.) --> not include double dots: ..

5 comments:

  1. Very informative post for mulesoft developers.You can also visit goformule.com for mulesoft stuff.

    ReplyDelete
  2. Glad I discovered this on google .
    You have shared amazing post. This post is really helpful for us to know the information. Thank you for taking your time to post such a wonderful article.Get for more information.
    Free Email Validation | Check Valid Email Address

    ReplyDelete


  3. I like your writing style really loving this website .
    Email Validation Tool

    ReplyDelete

Anypoint Studio Error: The project is missing Munit lIbrary to run tests

Anypoint Studio 7.9 has a bug. Even if we following the article: https://help.mulesoft.com/s/article/The-project-is-missing-MUnit-libraries-...