phone

package module
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 4, 2026 License: MIT Imports: 6 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

laravel-go-phone

CI Go reference docs Go 1.27

Go port of propaganistas/laravel-phone for parsing, validation, formatting and model storage.

Uses libphonenumber to check numbering-plan rules, format numbers for display and store phone numbers as E.164 or original text. The Go port follows propaganistas/laravel-phone.

Status: alpha.

Quick start

go get github.com/bowerbird-si/laravel-go-phone
package phone_test

import (
	"fmt"

	"github.com/bowerbird-si/laravel-go-phone"
)

func Example() {
	number, err := phone.Parse("0470 12 34 56", "BE")
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(number)
	// Output: +32470123456
}

Use the Laravel rule to validate a mobile number with a sibling country field.

package phonevalidation_test

import (
	"context"
	"fmt"

	phonevalidation "github.com/bowerbird-si/laravel-go-phone/validation"
	"go.laravel.com/validation"
	"go.laravel.com/validation/rule"
)

func Example() {
	form := struct {
		Phone   string `json:"phone"`
		Country string `json:"phone_country"`
	}{Phone: "0470 12 34 56", Country: "BE"}

	errs, err := validation.Validate(context.Background(), &form,
		rule.Field(&form.Phone, rule.Required, phonevalidation.Rule().Mobile()),
	)
	fmt.Println(len(errs), err)
	// Output: 0 <nil>
}

CI runs both examples. See getting started for model storage and country hints.

PHP parity

Follows propaganistas/laravel-phone 6.1.0 (commit 7433d79ea4b1).

Parity level Abilities Covered Diverged Planned PHP fixtures Last verified
full 51 30 21 0 166 2026-12-04

Every ability is listed in parity.toml, with the tests that cover it or the reason it differs.

Differences from PHP

  • The parser accepts additional Unicode decimal digits, such as Devanagari. Its 250-byte input limit can reject long, multibyte-padded text accepted by PHP. These rules also apply when detecting a region, validating, or formatting.

  • WithLeniency returns a new value. The original keeps its country hints and mode.

  • The parsed libphonenumber object is private. Parse the RFC3966 output with libphonenumber if you need that object, including its extension.

  • JSON always represents E.164 as a string, including the leading plus sign. PHP's JSON_NUMERIC_CHECK flag can turn it into a number.

  • Go text encoding stores the E.164 string. Decode that text or JSON to restore a number.

  • Add application behavior with ordinary functions. Go method sets are fixed at compile time.

  • Use New to construct a value and FormatNumber to format raw text in one call.

Validation
  • Attach a typed rule directly with rule.Field. Use the builder for countries and number types, and DefaultCountries for defaults on an individual rule.
  • The rule requires string values. Laravel skips null for a non-implicit rule, and a non-string dependent country produces a normal field failure. Laravel Phone issue #284
  • Use rule.Message for a localized message. The application supplies the translation.
  • RootCountryField reads an explicit path from request data. Use CountryField for paths relative to a nested form. Laravel for Go issue #429
Model storage
  • Pass country hints and values from sibling columns explicitly. A raw field resolves its number after the row is read.
  • E.164 model writes require a detectable region. This prevents a write that would fail on a subsequent read.
  • The stored text "0" is malformed for E.164 and fails raw number conversion. A raw field can still store and serialize that text.
  • A nil raw field writes SQL NULL and serializes as JSON null. Empty raw text stays a string in storage and JSON.

Installation and configuration

Install the module with go get github.com/bowerbird-si/laravel-go-phone. The guide shows rule options and model field types.

Compatibility

Module Framework Go
github.com/bowerbird-si/laravel-go-phone go.laravel.com v0.2.0 1.27

18 tests · 166 PHP fixtures (counted by kit readme)

Contributing

Issues and pull requests are welcome, of any size: bug reports, failing test cases, docs fixes, new features. Contributions written with AI coding agents are welcome too; please say what you checked. Run scripts/kit ci before opening a pull request, and see CONTRIBUTING.md. If you aren't sure, open an issue first.

Credits

Based on propaganistas/laravel-phone. Its licence notice is in NOTICE. Number parsing and metadata come from nyaruka/phonenumbers.

Status and licence

Maintenance status: active. MIT licensed, see LICENSE.

Community package, not affiliated with Laravel.

Documentation

Overview

Package phone is the Go port of propaganistas/laravel-phone for phone number parsing, validation, formatting and model storage.

It is a port of propaganistas/laravel-phone (https://github.com/Propaganistas/Laravel-Phone) to Laravel for Go.

Example
number, err := phone.Parse("0470 12 34 56", "BE")
if err != nil {
	fmt.Println(err)
	return
}
fmt.Println(number)
Output:
+32470123456

Index

Examples

Constants

This section is empty.

Variables

View Source
var ErrInvalidCountry = errors.New("phone: unsupported dialing country")

ErrInvalidCountry means a dialing origin is not a supported geographic region.

View Source
var ErrInvalidFormat = errors.New("phone: unsupported format")

ErrInvalidFormat means the format is outside PHP's PhoneNumberFormat enumeration.

View Source
var ErrInvalidType = errors.New("phone: unsupported number type")

ErrInvalidType means the type is outside PHP's PhoneNumberType enumeration.

View Source
var ErrUnparseable = errors.New("phone: cannot parse number")

ErrUnparseable means libphonenumber could not parse the input using the supplied hints.

Functions

func FormatNumber

func FormatNumber(raw string, format Format, countries ...string) (string, error)

FormatNumber formats raw input in one call, like PHP's phone helper with a format.

func ValidCountry

func ValidCountry(country string) bool

ValidCountry accepts the same supported, case-insensitive region codes as PHP's isValidCountry. The non-geographic region "001" is not a geographic hint.

Types

type Format

type Format string

Format is a format from PHP's PhoneNumberFormat enumeration.

const (
	// E164 is a plus-prefixed international number without spaces or extension.
	E164 Format = "E164"
	// International is a formatted number with its international calling code.
	International Format = "INTERNATIONAL"
	// National is a formatted number as dialed domestically.
	National Format = "NATIONAL"
	// RFC3966 is a telephone URI, including the extension if present.
	RFC3966 Format = "RFC3966"
)

func ParseFormat

func ParseFormat(name string) (Format, error)

ParseFormat is PHP's normalizeFormat. It accepts a case-insensitive name.

type Number

type Number struct {
	// contains filtered or unexported fields
}

Number is the Go equivalent of PHP's PhoneNumber. It keeps the original input, and is safe to copy and share. The zero value represents absence.

func New

func New(raw string, countries ...string) Number

New wraps raw text like PHP's PhoneNumber constructor. Use Parse to get a parse error up front, or New to retain the text for display on failure.

func Parse

func Parse(raw string, countries ...string) (Number, error)

Parse constructs a Number and reports whether it can be parsed. A parseable value may still fail Valid. Country hints are tried in order for national input.

func (Number) Country

func (n Number) Country() string

Country is PHP's getCountry. It returns an empty string when the region cannot be determined, or "001" for global services.

func (Number) E164

func (n Number) E164() (string, error)

E164 is PHP's formatE164.

func (Number) Equal

func (n Number) Equal(other Number) bool

Equal is PHP's equals. It compares E.164 values, ignoring extensions. An unparseable value never matches, including another copy of itself.

func (Number) Format

func (n Number) Format(format Format) (string, error)

Format is PHP's PhoneNumber::format. Choose a format constant or use ParseFormat to resolve a name such as "national".

func (Number) FormatForCountry

func (n Number) FormatForCountry(country string) (string, error)

FormatForCountry is PHP's formatForCountry. It formats the number as dialed from the given geographic region.

func (Number) FormatForMobileDialing

func (n Number) FormatForMobileDialing(country string, withFormatting bool) (string, error)

FormatForMobileDialing is PHP's formatForMobileDialingInCountry. It may return an empty string without error when the number cannot be dialed.

func (Number) InCountry

func (n Number) InCountry(countries ...string) bool

InCountry is PHP's isOfCountry. It resolves the original text again with the supplied hints, then checks whether the detected region is among them.

func (Number) International

func (n Number) International() (string, error)

International is PHP's formatInternational.

func (Number) IsType

func (n Number) IsType(types ...Type) (bool, error)

IsType is PHP's isOfType. FixedLine and Mobile also match FixedLineOrMobile.

func (Number) IsZero

func (n Number) IsZero() bool

IsZero reports whether n is the zero value and represents absence.

func (Number) MarshalJSON

func (n Number) MarshalJSON() ([]byte, error)

MarshalJSON is PHP's jsonSerialize and toJson. It emits an E.164 string for a parseable number or null for the zero value.

func (Number) MarshalText

func (n Number) MarshalText() ([]byte, error)

MarshalText encodes the E.164 value, the contents of PHP's serialized number.

func (Number) National

func (n Number) National() (string, error)

National is PHP's formatNational.

func (Number) NotEqual

func (n Number) NotEqual(other Number) bool

NotEqual is PHP's notEquals. It returns the inverse of Equal.

func (Number) Possible

func (n Number) Possible() bool

Possible checks the libphonenumber length rules, as in PHP's lenient isValid.

func (Number) RFC3966

func (n Number) RFC3966() (string, error)

RFC3966 is PHP's formatRFC3966.

func (Number) Raw

func (n Number) Raw() string

Raw is PHP's getRawNumber. It returns the original text without normalization.

func (Number) String

func (n Number) String() string

String is PHP's __toString. It returns E.164 or the original input on a parse error.

func (Number) Type

func (n Number) Type() (Type, error)

Type is PHP's getType. For a parseable value outside a known range, it returns Unknown without an error.

func (*Number) UnmarshalJSON

func (n *Number) UnmarshalJSON(data []byte) error

UnmarshalJSON reads an international number or null. On failure it leaves n unchanged.

func (*Number) UnmarshalText

func (n *Number) UnmarshalText(text []byte) error

UnmarshalText reads an international number. On failure it leaves n unchanged.

func (Number) Valid

func (n Number) Valid() bool

Valid is PHP's isValid. Strict mode checks the number in its selected region. Lenient mode checks whether its length is possible for the numbering plan.

func (Number) WithLeniency

func (n Number) WithLeniency(enable bool) Number

WithLeniency is the value-copy equivalent of PHP's lenient method. In lenient mode, national region selection and Valid use the possibility test.

type Type

type Type string

Type is a type name from PHP's PhoneNumberType enumeration.

const (
	// FixedLine identifies fixed-line numbers.
	FixedLine Type = "FIXED_LINE"
	// Mobile identifies mobile numbers.
	Mobile Type = "MOBILE"
	// FixedLineOrMobile covers ranges where the two types cannot be distinguished.
	FixedLineOrMobile Type = "FIXED_LINE_OR_MOBILE"
	// TollFree identifies freephone numbers.
	TollFree Type = "TOLL_FREE"
	// PremiumRate identifies premium-rate numbers.
	PremiumRate Type = "PREMIUM_RATE"
	// SharedCost identifies shared-cost numbers.
	SharedCost Type = "SHARED_COST"
	// VoIP identifies voice-over-IP numbers.
	VoIP Type = "VOIP"
	// PersonalNumber identifies personal numbers that can route calls.
	PersonalNumber Type = "PERSONAL_NUMBER"
	// Pager identifies pager numbers.
	Pager Type = "PAGER"
	// UAN identifies universal access numbers.
	UAN Type = "UAN"
	// Voicemail identifies voice-mail access numbers.
	Voicemail Type = "VOICEMAIL"
	// Unknown identifies numbers that match no known type.
	Unknown Type = "UNKNOWN"
	// Emergency is a PHP type name for short emergency codes.
	Emergency Type = "EMERGENCY"
	// ShortCode is a PHP type name for short numbers.
	ShortCode Type = "SHORT_CODE"
	// StandardRate is a PHP type name for short numbers charged at standard rate.
	StandardRate Type = "STANDARD_RATE"
)

func ParseType

func ParseType(name string) (Type, error)

ParseType is PHP's normalizeType. It accepts a case-insensitive name.

Directories

Path Synopsis
Package phonemodel provides raw and E.164 model fields for Laravel for Go.
Package phonemodel provides raw and E.164 model fields for Laravel for Go.
Package phonevalidation integrates phone number validation with Laravel for Go.
Package phonevalidation integrates phone number validation with Laravel for Go.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL