Drill

ProblemsGo › validation

Normalise a phone number

mediumvalidationStringsParsingGo

People type phone numbers however they like. The CRM stores exactly one shape, so the importer either produces that shape or rejects the row.

normalisePhone(raw: string, countryCode: string) → string?

Go needs a compiler and Drill does not host one yet, so this page is the reference rather than an exercise: the problem, worked examples, and the solution in full. To type it out, the same problem runs in Python.

Solve it in Python →

Where you start

func normalisePhone(raw string, countryCode string) *string {
	
}

Worked examples

CallResult
normalisePhone("0532 123 45 67", "90")pStr("+905321234567")
normalisePhone("532-123-4567", "90")pStr("+905321234567")
normalisePhone("(532) 123 45 67", "1")pStr("+15321234567")
normalisePhone("123", "90")nil

Hint

Clean, then drop the leading zero, then check the length. Three steps in that order.

Reference solution in Go
func normalisePhone(raw string, countryCode string) *string {
	if len(countryCode) < 1 || len(countryCode) > 3 {
		return nil
	}
	for i := 0; i < len(countryCode); i++ {
		if countryCode[i] < '0' || countryCode[i] > '9' {
			return nil
		}
	}
	d := ""
	for i := 0; i < len(raw); i++ {
		if raw[i] >= '0' && raw[i] <= '9' {
			d += string(raw[i])
		}
	}
	if strings.HasPrefix(d, "0") {
		d = d[1:]
	}
	if len(d) != 10 {
		return nil
	}
	result := "+" + countryCode + d
	return &result
}

The same problem in another language

More validation problems in Go