01/10/2010

Using Regex to validate CNPJ number

This regular expressions matches CNPJ number. CNPJ is a Registration Number of Brazilian Companies.


REPORT ZADN_SAMPLE.

*----------------------------------------------------------------------*
* -> CLASS cl_regex_test DEFINITION
*----------------------------------------------------------------------*
CLASS cl_regex_test DEFINITION FINAL.

PUBLIC SECTION.

METHODS : check_cnpj IMPORTING p_cnpj TYPE string.

PRIVATE SECTION.

DATA: o_regex TYPE REF TO cl_abap_regex,
o_matcher TYPE REF TO cl_abap_matcher.

ENDCLASS. "cl_regex_test DEFINITION

*----------------------------------------------------------------------*
* -> CLASS cl_regex_test IMPLEMENTATION
*----------------------------------------------------------------------*
CLASS cl_regex_test IMPLEMENTATION.

METHOD check_cnpj.

* Create the regular expression:

CREATE OBJECT o_regex
EXPORTING
pattern = '\d{2}.?\d{3}.?\d{3}/?\d{4}-?\d{2}'.

* Check to see if the CNPJ number matches the regular expression:

CREATE OBJECT o_matcher
EXPORTING
regex = o_regex
text = p_cnpj.

IF o_matcher->match( ) NE abap_true.

MESSAGE 'Enter valid CNPJ number...' TYPE 'E'.

ELSE.

MESSAGE 'This is a valid CNPJ number...' TYPE 'S'.

ENDIF.

ENDMETHOD. "check_cnpj

ENDCLASS. "cl_regex_test IMPLEMENTATION

************************************************************************
************************************************************************
* *
* PROGRAM FLOW LOGIC *
* *
************************************************************************

START-OF-SELECTION.

DATA : ocl_regex_test TYPE REF TO cl_regex_test.

CREATE OBJECT ocl_regex_test.

ocl_regex_test->check_cnpj( '12.043.129/0001-98' ). " IS VALID

"ocl_regex_test->check_cnpj( '02.025.659/0001-981' ). " IS INVALID

Nenhum comentário:

Postar um comentário