NetLife Guru

Open source Go packages for fast, maintainable web systems. Built with a documentation-first approach.

Product
OverviewGolang packagesNews
Documentation
DocumentationGo LoggerGo RouterGo DB Form
Company
OverviewContactNewsGitHub
Community / Support
Supportinfo@netlife.guru
© 2026 NetLife Guru. All rights reserved.
GitHubinfo@netlife.guru
NetLife GuruNetLife GuruNetLife Guru
NetLife GuruNetLife GuruNetLife Guru
OverviewDocumentationNewsSupportContact

Golang packages

About
Validation RulesBoolean RulesFloat64 RulesInteger RulesString RulesTime RulesRequired RulesSlice RulesFormat RulesGeneric RulesCompare Rules
Form ValidatorRules

String Rules

Learn how to validate string fields in NLG Form using required checks, length validation, prefixes, suffixes, substrings, equality rules, and custom validation codes.

String rules validate typed string fields defined with form.Str.

They are useful for validating usernames, passwords, emails, titles, slugs, identifiers, API keys, tokens, labels, descriptions, URLs, and other text-based application input.

Common Use Cases

String rules are commonly used for:

  • usernames and passwords
  • email addresses
  • search queries
  • API tokens and keys
  • slugs and identifiers
  • titles and descriptions
  • frontend form validation
  • URL fragments
  • tags and labels
  • configuration values

TL;DR

RuleDescription
rules.Required(field)Requires the string to be non-empty
rules.RequiredWithCode(field, code)Same as Required with a custom error code
rules.MinLen(field, n)Requires the string length to be at least n
rules.MinLenWithCode(field, n, code)Same as MinLen with a custom error code
rules.MaxLen(field, n)Requires the string length to be at most n
rules.MaxLenWithCode(field, n, code)Same as MaxLen with a custom error code
rules.Len(field, n)Requires the string length to exactly match n
rules.LenWithCode(field, n, code)Same as Len with a custom error code
rules.Contains(field, value)Requires the string to contain a substring
rules.ContainsWithCode(field, value, code)Same as Contains with a custom error code
rules.HasPrefix(field, prefix)Requires the string to start with a prefix
rules.HasPrefixWithCode(field, prefix, code)Same as HasPrefix with a custom error code
rules.HasSuffix(field, suffix)Requires the string to end with a suffix
rules.HasSuffixWithCode(field, suffix, code)Same as HasSuffix with a custom error code
rules.StringEquals(field, expected)Requires the string to exactly match the expected value
rules.StringEqualsWithCode(field, expected, code)Same as StringEquals with a custom error code
rules.NotEmpty(field)Alias-style helper for non-empty validation
rules.IsString(field)Validates that the field contains a string value

Defining String Fields

String validation starts by defining typed string fields.

StringForm := struct {
	Username form.StringField[StringRulesRequest]
	Password form.StringField[StringRulesRequest]
	Slug     form.StringField[StringRulesRequest]
}{
	Username: form.Str[StringRulesRequest]("username", func(r *StringRulesRequest) string {
		return r.Username
	}),
	Password: form.Str[StringRulesRequest]("password", func(r *StringRulesRequest) string {
		return r.Password
	}),
	Slug: form.Str[StringRulesRequest]("slug", func(r *StringRulesRequest) string {
		return r.Slug
	}),
}

Each field contains:

  • the validation response field name
  • typed accessors
  • reusable schema references
  • strongly typed string access

Applying String Rules

String rules are attached directly to typed field references.

return form.Schema[StringRulesRequest]{
	rules.Required(StringForm.Username),
	rules.MinLen(StringForm.Password, 8),
	rules.HasPrefix(StringForm.Slug, "app-"),
}

This keeps validation logic:

  • explicit
  • reusable
  • composable
  • transport-independent
  • type-safe

Rule Examples

Required

Requires the string value to be non-empty.

rules.Required(StringForm.Username)

Typical use cases:

  • usernames
  • passwords
  • email fields
  • required request data

RequiredWithCode

Requires the string to be non-empty and returns a custom validation code.

const CodeUsernameRequired = form.Code("username_required")

rules.RequiredWithCode(
	StringForm.Username,
	CodeUsernameRequired,
)

Useful for frontend-friendly API validation responses.


MinLen

Requires the string length to be greater than or equal to the minimum length.

rules.MinLen(StringForm.Password, 8)

Typical use cases:

  • password policies
  • usernames
  • API keys
  • minimum descriptions

MinLenWithCode

Requires the string to meet the minimum length and returns a custom validation code.

const CodePasswordTooShort = form.Code("password_too_short")

rules.MinLenWithCode(
	StringForm.Password,
	8,
	CodePasswordTooShort,
)

MaxLen

Requires the string length to stay below the specified maximum length.

rules.MaxLen(StringForm.Username, 32)

Typical use cases:

  • usernames
  • labels
  • identifiers
  • database constraints

MaxLenWithCode

Requires the string length to stay below the maximum and returns a custom validation code.

const CodeUsernameTooLong = form.Code("username_too_long")

rules.MaxLenWithCode(
	StringForm.Username,
	32,
	CodeUsernameTooLong,
)

Len

Requires the string length to exactly match the specified value.

rules.Len(StringForm.Token, 64)

Typical use cases:

  • hashes
  • tokens
  • identifiers
  • fixed-length values

LenWithCode

Requires the string length to exactly match the expected length and returns a custom validation code.

const CodeInvalidTokenLength = form.Code("invalid_token_length")

rules.LenWithCode(
	StringForm.Token,
	64,
	CodeInvalidTokenLength,
)

Contains

Requires the string to contain a substring.

rules.Contains(StringForm.Email, "@")

Typical use cases:

  • simple email checks
  • keyword validation
  • token prefixes
  • partial matching

ContainsWithCode

Requires the string to contain the substring and returns a custom validation code.

const CodeMissingAtSymbol = form.Code("missing_at_symbol")

rules.ContainsWithCode(
	StringForm.Email,
	"@",
	CodeMissingAtSymbol,
)

HasPrefix

Requires the string to start with a specific prefix.

rules.HasPrefix(StringForm.Slug, "app-")

Typical use cases:

  • route slugs
  • internal identifiers
  • namespaced values
  • prefixed tokens

HasPrefixWithCode

Requires the string to start with the specified prefix and returns a custom validation code.

const CodeInvalidPrefix = form.Code("invalid_prefix")

rules.HasPrefixWithCode(
	StringForm.Slug,
	"app-",
	CodeInvalidPrefix,
)

HasSuffix

Requires the string to end with a specific suffix.

rules.HasSuffix(StringForm.File, ".json")

Typical use cases:

  • file extensions
  • domain validation
  • suffix-based identifiers

HasSuffixWithCode

Requires the string to end with the specified suffix and returns a custom validation code.

const CodeInvalidSuffix = form.Code("invalid_suffix")

rules.HasSuffixWithCode(
	StringForm.File,
	".json",
	CodeInvalidSuffix,
)

StringEquals

Requires the string to exactly match the expected value.

rules.StringEquals(StringForm.Role, "admin")

Useful for fixed application states and strict API contracts.


StringEqualsWithCode

Requires the string to exactly match the expected value and returns a custom validation code.

const CodeInvalidRole = form.Code("invalid_role")

rules.StringEqualsWithCode(
	StringForm.Role,
	"admin",
	CodeInvalidRole,
)

NotEmpty

Validates that the string is not empty.

rules.NotEmpty(StringForm.Username)

This helper is typically used as a semantic alternative to Required.


IsString

Checks whether the field contains a valid string value.

rules.IsString(StringForm.Username)

For typed Go structures this rule is mostly useful for API symmetry because invalid JSON string types are usually rejected during request decoding before schema validation begins.

Complete Example

package main

import (
	"github.com/netlifeguru/form"
	"github.com/netlifeguru/form/rules"
)

type StringRulesRequest struct {
	Username string `json:"username"`
	Password string `json:"password"`
	Slug     string `json:"slug"`
}

func StringRulesSchema() form.Schema[StringRulesRequest] {
	StringForm := struct {
		Username form.StringField[StringRulesRequest]
		Password form.StringField[StringRulesRequest]
		Slug     form.StringField[StringRulesRequest]
	}{
		Username: form.Str[StringRulesRequest]("username", func(r *StringRulesRequest) string {
			return r.Username
		}),
		Password: form.Str[StringRulesRequest]("password", func(r *StringRulesRequest) string {
			return r.Password
		}),
		Slug: form.Str[StringRulesRequest]("slug", func(r *StringRulesRequest) string {
			return r.Slug
		}),
	}

	return form.Schema[StringRulesRequest]{
		rules.Required(StringForm.Username),
		rules.MinLen(StringForm.Password, 8),
		rules.HasPrefix(StringForm.Slug, "app-"),
	}
}

Notes

  • String rules operate on typed Go string values.
  • Invalid JSON types are rejected before validation begins.
  • Use MinLen and MaxLen for boundary validation instead of manual string checks.
  • Use custom error codes for stable frontend-facing validation contracts.
  • String validation rules remain reusable across APIs, background jobs, CLI tools, and internal services.
  • Validation logic stays explicit and independent from transport layers.
  • String rules can be combined with format validators such as email, UUID, URL, JSON, and regex validation.

Integer Rules

Learn how to validate integer fields in NLG Form using minimum, maximum, range, equality, positivity, negativity, and custom validation rules.

Time Rules

Learn how to validate time.Time fields in NLG Form using before, after, range, equality, zero-value, and custom validation rules.

On this page

Common Use CasesTL;DRDefining String FieldsApplying String RulesRule ExamplesRequiredRequiredWithCodeMinLenMinLenWithCodeMaxLenMaxLenWithCodeLenLenWithCodeContainsContainsWithCodeHasPrefixHasPrefixWithCodeHasSuffixHasSuffixWithCodeStringEqualsStringEqualsWithCodeNotEmptyIsStringComplete ExampleNotes