Detect invalid UTF-8
Detect invalid UTF-8
Go strings may contain any bytes. Validate text with utf8.ValidString. utf8.DecodeRuneInString returns the first rune and its byte width. Invalid nonempty input at the start returns RuneError (U+FFFD) with width 1; empty input returns RuneError with width 0.
package main
import ( "fmt" "unicode/utf8")
func main() { for _, s := range []string{"\xff", "\uFFFD", ""} { r, n := utf8.DecodeRuneInString(s) fmt.Printf("%t %U %d\n", utf8.ValidString(s), r, n) }}A genuine replacement character is valid UTF-8 and occupies three bytes. Checking the rune alone cannot distinguish it from a decoding error; inspect the width. UTF-8 validity does not establish that text is safe or meaningful.
Expected output:
false U+FFFD 1true U+FFFD 3true U+FFFD 0Reject or repair invalid text explicitly
package main
import ( "fmt" "strings" "unicode/utf8")
func main() { s := "A\xff\xfeB" fmt.Println(utf8.ValidString(s)) fixed := strings.ToValidUTF8(s, "?") fmt.Println(fixed, utf8.ValidString(fixed))}ToValidUTF8 replaces each run of invalid bytes with the replacement. This loses original bytes. For strict validation, reject invalid input rather than silently repairing it. The replacement itself must be valid to guarantee valid output.
Expected output:
falseA?B trueTry it locally
Check "ok" and a string containing byte 0xff; print validity and repair the latter with "!".
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Strings and Unicode 05: Detect invalid UTF-8
Check the lesson objective before moving on.
Which pair indicates invalid nonempty UTF-8 at the start?
How many replacements does ToValidUTF8 use for one consecutive run of invalid bytes?