001/*
002 *   Copyright 2024 Vonage
003 *
004 *   Licensed under the Apache License, Version 2.0 (the "License");
005 *   you may not use this file except in compliance with the License.
006 *   You may obtain a copy of the License at
007 *
008 *        http://www.apache.org/licenses/LICENSE-2.0
009 *
010 *   Unless required by applicable law or agreed to in writing, software
011 *   distributed under the License is distributed on an "AS IS" BASIS,
012 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 *   See the License for the specific language governing permissions and
014 *   limitations under the License.
015 */
016package com.vonage.client.common;
017
018import com.fasterxml.jackson.annotation.JsonValue;
019import java.util.Objects;
020import java.util.regex.Pattern;
021
022/**
023 * Utility class for validating and sanitising phone numbers to be compliant with the E164 format.
024 */
025public class E164 {
026        static final Pattern PATTERN = Pattern.compile("[1-9]\\d{6,14}");
027
028        private final String number;
029
030        public E164(String number) {
031                Objects.requireNonNull(number, "Number cannot be null");
032                String sanitized = number.replace(" ", "").replace("-","");
033                if (sanitized.startsWith("+")) {
034                        sanitized = sanitized.substring(1);
035                }
036                if (PATTERN.matcher(sanitized).matches()) {
037                        this.number = sanitized;
038                }
039                else {
040                        throw new IllegalArgumentException("Malformed E.164 number: "+number);
041                }
042        }
043
044        @JsonValue
045        @Override
046        public String toString() {
047                return number;
048        }
049}