Validating Email Using Regular Expression in ABAP

Summary: in this tutorial, you will learn how to validate email by using regular expression in ABAP.

In some cases, you have to validate email addresses from the screen field, Web Dynpro input field, or text from an uploaded file. The validation makes sure that you have a valid email format for further processing such as sending out a notification or storing it in the database.

SAP provides a very useful API for you to validate the email address by using the regular expression. The steps of validating email as follows:

  • First, compose a regular expression that matches an email address.
  • Then, create an instance of class cl_abap_regex with the email address pattern called regex object.
  • Third, create a matcher object, which is an instance of class cl_abap_matcher, from the regex object above and call the method match() method of the matcher object. If the returned value of the match() method is not initial, the email address is valid. Otherwise, it is invalid.

It is important to understand that the steps of validating the email above are not only applied to validating email but also are relevant to validate anything that matches a regular expression.

The following shows the program that validates an email address:

REPORT  zvalidateemail.

DATA: go_regex   TYPE REF TO cl_abap_regex,
      go_matcher TYPE REF TO cl_abap_matcher,
      go_match   TYPE c LENGTH 1,
      gv_msg     TYPE string.

PARAMETERS: p_email TYPE ad_smtpadr.

START-OF-SELECTION.

  CREATE OBJECT go_regex
    EXPORTING
      pattern     = '\w+(\.\w+)*@(\w+\.)+(\w{2,4})'
      ignore_case = abap_true.

  go_matcher = go_regex->create_matcher( text = p_email ).

  IF go_matcher->match( ) IS INITIAL.
    gv_msg = 'Email address is invalid'.
  ELSE.
    gv_msg = 'Email address is valid'.
  ENDIF.

  MESSAGE gv_msg TYPE 'I'.