Sobes.tech
Senior

How to make a string validator not longer than 250 characters?

sobes.tech AI

Answer from AI

In Go, you can create a simple string validator that checks if the length does not exceed 250 characters, like this:

func ValidateStringLength(s string) error {
    if len(s) > 250 {
        return fmt.Errorf("string too long: %d characters, maximum 250", len(s))
    }
    return nil
}

// Usage:
err := ValidateStringLength(inputString)
if err != nil {
    // handle error
}

If you need to consider the number of characters in Unicode (runes), not bytes, it's better to use utf8.RuneCountInString:

import "unicode/utf8"

func ValidateStringLength(s string) error {
    if utf8.RuneCountInString(s) > 250 {
        return fmt.Errorf("string too long: more than 250 characters")
    }
    return nil
}