Validation of format (telephone number)
In this recipe, we will see how to use the back-referencing operator in order to validate telephone numbers. Suppose telephone numbers in a certain city follow the rule: a number must be of exactly eight digits, and the first and second digit must be the same.
For example, the valid numbers of the city may be 44005600
, 88008700
, and so on. If the number entered starts with a zero or has length less than eight, an error should be displayed. We will see how a short validation program may be written.
How to do it...
For creating the program that checks the validity of a telephone number according to the given criteria, proceed as follows:
- Declare a parameter having the name
tel_no
with eight characters. - We then use the
find regex
statement to search for the pattern([1-9])\1[0-9]{6}
in the telephone number entered by the user. - The
if
statement is then used for checking the return code. Forsy-subrc
, having the value0
, the messageNumber is Valid
is displayed.
How it works...
There are two parts of the regular expression that we created, that is, the regex for the first two digits and then for the remaining six digits. Let us look at this in detail.
The requirement is that the first and second number cannot be a zero. So, we have specified the range [1-9]
and not [0-9]
for the first number. We want the first number to be part of the first subgroup and hence the parenthesis is used. The first digit of the phone number that matches the [1-9]
part of the regex is stored in the first subgroup register. This value may be addressed using the back-referencing operator \1
. (Since, in this case, we have one subgroup, the corresponding placeholder for the value stored in the first register is \1
). Since the first and the second number must match, we use \1
in place of the second digit.
The next part is comparatively simple. For the remaining six digits of the telephone may include zeros as well, we use the [0-9]
range along with the length of 6
specified in curly brackets.
The find regex
statement tries to find the given regex in the eight-character telephone number. In case, a match is found, the return code sy-subrc
equals 0
, so we input the message Number is Valid
.