Skip to content

How to Validate Phone number in GoLang ?

IsPhoneNumberId checks if the given string is a valid Indonesian phone number.

Parameters:

  • input: The string to be validated.

Returns:

  • A boolean indicating whether the string is a valid phone number or not.

The function first removes any whitespace or dashes from the input string. Then it trims any non-digit characters from the input string, keeping only the digit characters and the "+" character, which is used to indicate the country code. The trimmed string is then matched against a regular expression pattern. If the trimmed string matches the pattern, the function returns true, otherwise it returns false.

import (
	"regexp"
	"strings"
)
func IsPhoneNumberId(input string) bool {
	input = strings.ReplaceAll(input, " ", "")
	input = strings.ReplaceAll(input, "-", "")
	// The pattern to match the phone number. It should start with "+" or "62" or "0", followed by "8" and then 9 digits.
	pattern := `^(\+62|62|0)(8)\d{9}$`

	// Trim the input string to remove any non-digit characters. This is done to handle cases where the input string contains
	// white spaces or any other non-digit characters.
	phoneNumber := strings.TrimFunc(input, func(r rune) bool {
		// Only keep digit characters and the "+" character, which is used to indicate the country code.
		return !('0' <= r && r <= '9' || r == '+')
	})

	// Check if the phone number matches the pattern using the regexp.MatchString function.
	// If there is an error during the matching process, return false.
	match, err := regexp.MatchString(pattern, phoneNumber)
	if err != nil {
		return false
	}

	// Return the match result, indicating whether the phone number is valid or not.
	return match
}

Experience the magic of coding unfold as you execute this code!

package main

import (
	"fmt"
	"regexp"
	"strings"
)

func IsPhoneNumberId(input string) bool {
	input = strings.ReplaceAll(input, " ", "")
	input = strings.ReplaceAll(input, "-", "")
	pattern := `^(\+62|62|0)(8)\d{9}$`
	phoneNumber := strings.TrimFunc(input, func(r rune) bool {
		return !('0' <= r && r <= '9' || r == '+')
	})

	match, err := regexp.MatchString(pattern, phoneNumber)
	if err != nil {
		return false
	}
	return match
}

func main() {
	if IsPhoneNumberId("089-1234-5678") {
		fmt.Println("089-1234-5678 is phone number id")
	}
	if IsPhoneNumberId("+6289-1234-5678") {
		fmt.Println("+6289-1234-5678 is phone number id")
	}
	if IsPhoneNumberId("6289-1234-5678") {
		fmt.Println("6289-1234-5678 is phone number id")
	}
	if IsPhoneNumberId("+6589-1234-5678") { // +62 country SG
		fmt.Println("+6589-1234-5678 is phone number id")
	}

	fmt.Println("Build with love by Adam Nasrudin")
}

enjoy your code!