validation

package
v0.0.0-...-14a125a Latest Latest
Warning

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

Go to latest
Published: Oct 21, 2025 License: MIT Imports: 15 Imported by: 0

README

validation - Fluent Validation for Go / Go를 위한 Fluent 검증

Go Version Coverage License Version

135+ validators to reduce 20-30 lines of validation code to just 1-2 lines with fluent API.

135개 이상의 검증기로 20-30줄의 검증 코드를 단 1-2줄로 줄입니다.

Design Philosophy / 설계 철학

"30 lines → 2 lines" - Extreme Simplicity

  • ⛓️ Fluent API with method chaining / 메서드 체이닝으로 Fluent API
  • 🛡️ Type-safe with Go generics / Go 제네릭으로 타입 안전
  • 🌐 Bilingual error messages (EN/KR) / 양방향 에러 메시지 (영어/한글)
  • 📦 Zero external dependencies / 외부 의존성 제로
  • ✅ 99.4% test coverage / 99.4% 테스트 커버리지
  • 🚀 Enterprise-grade quality / 엔터프라이즈급 품질

Quick Start / 빠른 시작

import "github.com/arkd0ng/go-utils/validation"

// Simple validation / 간단한 검증
v := validation.New("john@example.com", "email")
v.Required().Email()
if err := v.Validate(); err != nil {
    log.Fatal(err)
}

// Multiple validations with chaining / 체이닝으로 여러 검증
v := validation.New(25, "age")
v.Positive().Min(18).Max(120)
err := v.Validate()

// Multi-field validation / 다중 필드 검증
mv := validation.NewValidator()

mv.Field(user.Name, "name").Required().MinLength(2).MaxLength(50)
mv.Field(user.Email, "email").Required().Email()
mv.Field(user.Age, "age").Positive().Min(18).Max(120)

if err := mv.Validate(); err != nil {
    // Handle validation errors
}

All Validators by Category / 카테고리별 모든 검증기

1. Core Methods (10개) - validator.go
Method Description 설명
New(value, field) Create new validator 새 검증기 생성
Validate() Execute validation 검증 실행
GetErrors() Get all errors 모든 에러 가져오기
StopOnError() Stop on first error 첫 에러에서 중지
WithMessage(msg) Custom message 사용자 정의 메시지
WithCustomMessage(rule, msg) Pre-configure message 메시지 사전 설정
WithCustomMessages(map) Multiple messages 여러 메시지 설정
Custom(fn, msg) Custom validator 사용자 정의 검증기
NewValidator() Multi-field validator 다중 필드 검증기
Field(value, name) Add field to validator 검증기에 필드 추가
2. String Validators (19개) - rules_string.go
Validator Description 설명 Example
Required() Not empty 비어있지 않음 v.Required()
MinLength(n) Min string length 최소 길이 v.MinLength(3)
MaxLength(n) Max string length 최대 길이 v.MaxLength(50)
Length(n) Exact length 정확한 길이 v.Length(10)
Email() Valid email address 유효한 이메일 v.Email()
URL() Valid URL 유효한 URL v.URL()
Alpha() Only letters (a-z, A-Z) 문자만 v.Alpha()
Alphanumeric() Letters and numbers 문자와 숫자 v.Alphanumeric()
Numeric() Only numbers 숫자만 v.Numeric()
StartsWith(s) Starts with prefix 접두사로 시작 v.StartsWith("Mr.")
EndsWith(s) Ends with suffix 접미사로 끝남 v.EndsWith(".com")
Contains(s) Contains substring 부분 문자열 포함 v.Contains("@")
Regex(pattern) Match regex pattern 정규식 매칭 v.Regex("^[A-Z]")
UUID() Valid UUID 유효한 UUID v.UUID()
JSON() Valid JSON string 유효한 JSON v.JSON()
Base64() Valid Base64 유효한 Base64 v.Base64()
Lowercase() All lowercase 모두 소문자 v.Lowercase()
Uppercase() All uppercase 모두 대문자 v.Uppercase()
Phone() Valid phone number 유효한 전화번호 v.Phone()
3. Numeric Validators (10개) - rules_numeric.go
Validator Description 설명 Example
Min(n) Minimum value (≥) 최소값 v.Min(18)
Max(n) Maximum value (≤) 최대값 v.Max(120)
Between(min, max) Value range 값 범위 v.Between(1, 100)
Positive() Positive number (> 0) 양수 v.Positive()
Negative() Negative number (< 0) 음수 v.Negative()
Zero() Zero value (= 0) 0 v.Zero()
NonZero() Non-zero value (≠ 0) 0이 아님 v.NonZero()
Even() Even number 짝수 v.Even()
Odd() Odd number 홀수 v.Odd()
MultipleOf(n) Multiple of n n의 배수 v.MultipleOf(5)
4. Collection Validators (10개) - rules_collection.go
Validator Description 설명 Example
In(...values) Value in list 목록에 존재 v.In("red", "blue")
NotIn(...values) Value not in list 목록에 없음 v.NotIn("banned")
ArrayLength(n) Exact array length 정확한 배열 길이 v.ArrayLength(5)
ArrayMinLength(n) Min array length 최소 배열 길이 v.ArrayMinLength(1)
ArrayMaxLength(n) Max array length 최대 배열 길이 v.ArrayMaxLength(10)
ArrayNotEmpty() Array not empty 배열 비어있지 않음 v.ArrayNotEmpty()
ArrayUnique() Unique elements 고유한 요소 v.ArrayUnique()
MapHasKey(key) Map contains key 맵에 키 존재 v.MapHasKey("id")
MapHasKeys(...keys) Map has all keys 모든 키 존재 v.MapHasKeys("a", "b")
MapNotEmpty() Map not empty 맵 비어있지 않음 v.MapNotEmpty()
5. Comparison Validators (11개) - rules_comparison.go
Validator Description 설명 Example
Equals(value) Equal to value 값과 동일 v.Equals(100)
NotEquals(value) Not equal to value 값과 다름 v.NotEquals(0)
GreaterThan(n) Greater than (>) 보다 큼 v.GreaterThan(0)
GreaterThanOrEqual(n) Greater or equal (≥) 크거나 같음 v.GreaterThanOrEqual(18)
LessThan(n) Less than (<) 보다 작음 v.LessThan(100)
LessThanOrEqual(n) Less or equal (≤) 작거나 같음 v.LessThanOrEqual(120)
Before(time) Before time 시간 이전 v.Before(deadline)
After(time) After time 시간 이후 v.After(startTime)
BeforeOrEqual(time) Before or equal 시간 이전이거나 같음 v.BeforeOrEqual(now)
AfterOrEqual(time) After or equal 시간 이후이거나 같음 v.AfterOrEqual(minTime)
BetweenTime(start, end) Time range 시간 범위 v.BetweenTime(start, end)
6. Type Validators (7개) - rules_type.go
Validator Description 설명 Example
True() Boolean true boolean true v.True()
False() Boolean false boolean false v.False()
Nil() Value is nil nil임 v.Nil()
NotNil() Value not nil nil이 아님 v.NotNil()
Type(name) Specific type 특정 타입 v.Type("string")
Empty() Zero value 제로 값 v.Empty()
NotEmpty() Not zero value 제로 값 아님 v.NotEmpty()
7. Network Validators (5개) - rules_network.go
Validator Description 설명 Example
IPv4() Valid IPv4 address 유효한 IPv4 v.IPv4()
IPv6() Valid IPv6 address 유효한 IPv6 v.IPv6()
IP() Valid IP (v4 or v6) 유효한 IP v.IP()
CIDR() Valid CIDR notation 유효한 CIDR v.CIDR()
MAC() Valid MAC address 유효한 MAC 주소 v.MAC()
8. Date/Time Validators (4개) - rules_datetime.go
Validator Description 설명 Example
DateFormat(fmt) Date string format 날짜 문자열 형식 v.DateFormat("2006-01-02")
TimeFormat(fmt) Time string format 시간 문자열 형식 v.TimeFormat("15:04:05")
DateBefore(time) Date before 날짜 이전 v.DateBefore(deadline)
DateAfter(time) Date after 날짜 이후 v.DateAfter(startDate)
9. File Validators (6개) - rules_file.go
Validator Description 설명 Example
FilePath() Valid file path 유효한 파일 경로 v.FilePath()
FileExists() File exists 파일 존재 v.FileExists()
FileReadable() File is readable 읽기 가능 v.FileReadable()
FileWritable() File is writable 쓰기 가능 v.FileWritable()
FileSize(min, max) File size range 파일 크기 범위 v.FileSize(100, 1000000)
FileExtension(...exts) File extension 파일 확장자 v.FileExtension(".jpg", ".png")
10. Security Validators (6개) - rules_security.go
Validator Description 설명 Example
JWT() Valid JWT token 유효한 JWT v.JWT()
BCrypt() Valid BCrypt hash 유효한 BCrypt v.BCrypt()
MD5() Valid MD5 hash 유효한 MD5 v.MD5()
SHA1() Valid SHA1 hash 유효한 SHA1 v.SHA1()
SHA256() Valid SHA256 hash 유효한 SHA256 v.SHA256()
SHA512() Valid SHA512 hash 유효한 SHA512 v.SHA512()
11. Credit Card Validators (3개) - rules_creditcard.go
Validator Description 설명 Example
CreditCard() Valid credit card 유효한 신용카드 v.CreditCard()
CreditCardType(type) Specific card type 특정 카드 타입 v.CreditCardType("visa")
Luhn() Luhn algorithm Luhn 알고리즘 v.Luhn()
12. Business Code Validators (3개) - rules_business.go
Validator Description 설명 Example
ISBN() Valid ISBN-10/13 유효한 ISBN v.ISBN()
ISSN() Valid ISSN-8 유효한 ISSN v.ISSN()
EAN() Valid EAN-8/13 유효한 EAN v.EAN()
13. Color Validators (4개) - rules_color.go
Validator Description 설명 Example
HexColor() Hex color code 16진수 색상 v.HexColor()
RGB() RGB color format RGB 색상 v.RGB()
RGBA() RGBA color format RGBA 색상 v.RGBA()
HSL() HSL color format HSL 색상 v.HSL()
14. Data Format Validators (4개) - rules_data.go
Validator Description 설명 Example
ASCII() ASCII characters only ASCII 문자만 v.ASCII()
Printable() Printable ASCII 출력 가능 ASCII v.Printable()
Whitespace() Whitespace only 공백만 v.Whitespace()
AlphaSpace() Letters and spaces 문자와 공백 v.AlphaSpace()
15. Format Validators (3개) - rules_format.go
Validator Description 설명 Example
UUIDv4() Valid UUID v4 유효한 UUID v4 v.UUIDv4()
XML() Valid XML 유효한 XML v.XML()
Hex() Hexadecimal string 16진수 문자열 v.Hex()
16. Geographic Validators (3개) - rules_geographic.go
Validator Description 설명 Example
Latitude() Valid latitude 유효한 위도 v.Latitude()
Longitude() Valid longitude 유효한 경도 v.Longitude()
Coordinate() Valid coordinate 유효한 좌표 v.Coordinate()
17. Logical Validators (4개) - rules_logical.go
Validator Description 설명 Example
OneOf(...values) One of values 값 중 하나 v.OneOf("a", "b", "c")
NotOneOf(...values) Not one of values 값 중 하나가 아님 v.NotOneOf("banned")
When(bool, fn) Conditional validation 조건부 검증 v.When(true, func(v) {...})
Unless(bool, fn) Inverse conditional 역 조건부 검증 v.Unless(false, func(v) {...})
18. Range Validators (3개) - rules_range.go
Validator Description 설명 Example
IntRange(min, max) Integer range 정수 범위 v.IntRange(1, 100)
FloatRange(min, max) Float range 실수 범위 v.FloatRange(0.0, 1.0)
DateRange(start, end) Date range 날짜 범위 v.DateRange(start, end)

Advanced Features / 고급 기능

Stop on First Error / 첫 에러에서 중지
v := validation.New("", "email")
v.StopOnError().Required().Email().MaxLength(100)
// Stops at Required() if empty, doesn't check Email()
// 비어있으면 Required()에서 중지, Email()은 검사하지 않음
Custom Error Messages / 사용자 정의 에러 메시지
// Per-rule message / 규칙별 메시지
v := validation.New(user.Age, "age")
v.Min(18).WithMessage("You must be at least 18 years old")
v.Max(120).WithMessage("Invalid age")

// Pre-configured messages / 사전 설정 메시지
v := validation.New(user.Email, "email")
v.WithCustomMessage("required", "Email is required")
v.WithCustomMessage("email", "Please enter a valid email")
v.Required().Email()

// Multiple messages at once / 여러 메시지 한 번에
v.WithCustomMessages(map[string]string{
    "required": "This field is required",
    "email": "Invalid email format",
    "max_length": "Too long",
})
Custom Validators / 사용자 정의 검증기
v := validation.New(password, "password")
v.Custom(func(val interface{}) bool {
    s := val.(string)
    return strings.ContainsAny(s, "!@#$%^&*()")
}, "Password must contain at least one special character")

Real-World Examples / 실제 사용 예제

User Registration / 사용자 등록
type User struct {
    Username  string
    Email     string
    Password  string
    Age       int
    Country   string
    Website   string
    Phone     string
}

func ValidateUser(user User) error {
    mv := validation.NewValidator()

    mv.Field(user.Username, "username").
        Required().
        MinLength(3).
        MaxLength(20).
        Alphanumeric()

    mv.Field(user.Email, "email").
        Required().
        Email().
        MaxLength(100)

    mv.Field(user.Password, "password").
        Required().
        MinLength(8).
        MaxLength(100).
        Regex(`^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]`)

    mv.Field(user.Age, "age").
        Positive().
        Between(13, 120)

    mv.Field(user.Country, "country").
        Required().
        In("US", "KR", "JP", "CN", "UK", "FR", "DE")

    mv.Field(user.Website, "website").
        URL()  // Optional field, only validates if not empty

    mv.Field(user.Phone, "phone").
        Phone()

    return mv.Validate()
}
API Request Validation / API 요청 검증
type CreatePostRequest struct {
    Title       string
    Content     string
    Tags        []string
    Category    string
    PublishDate time.Time
    AuthorID    string
    Attachments []string
}

func ValidateCreatePost(req CreatePostRequest) error {
    mv := validation.NewValidator()

    mv.Field(req.Title, "title").
        Required().
        MinLength(5).
        MaxLength(100)

    mv.Field(req.Content, "content").
        Required().
        MinLength(20).
        MaxLength(5000)

    mv.Field(req.Tags, "tags").
        ArrayNotEmpty().
        ArrayMinLength(1).
        ArrayMaxLength(5).
        ArrayUnique()

    mv.Field(req.Category, "category").
        Required().
        In("tech", "business", "lifestyle", "news", "sports")

    mv.Field(req.PublishDate, "publish_date").
        After(time.Now())

    mv.Field(req.AuthorID, "author_id").
        Required().
        UUID()

    mv.Field(req.Attachments, "attachments").
        ArrayMaxLength(10)

    return mv.Validate()
}
Configuration Validation / 설정 검증
type ServerConfig struct {
    Port         int
    Host         string
    DatabaseURL  string
    RedisURL     string
    Timeout      int
    MaxConns     int
    Features     map[string]bool
    TLSCert      string
    TLSKey       string
    AllowedIPs   []string
}

func ValidateConfig(cfg ServerConfig) error {
    mv := validation.NewValidator()

    mv.Field(cfg.Port, "port").
        Positive().
        Between(1, 65535)

    mv.Field(cfg.Host, "host").
        Required().
        URL()

    mv.Field(cfg.DatabaseURL, "database_url").
        Required().
        StartsWith("postgres://").
        URL()

    mv.Field(cfg.RedisURL, "redis_url").
        Required().
        StartsWith("redis://").
        URL()

    mv.Field(cfg.Timeout, "timeout").
        Positive().
        Between(1, 3600)

    mv.Field(cfg.MaxConns, "max_connections").
        Positive().
        Between(10, 10000)

    mv.Field(cfg.Features, "features").
        MapNotEmpty().
        MapHasKeys("authentication", "logging", "monitoring")

    mv.Field(cfg.TLSCert, "tls_cert").
        FileExists().
        FileReadable().
        FileExtension(".pem", ".crt")

    mv.Field(cfg.TLSKey, "tls_key").
        FileExists().
        FileReadable().
        FileExtension(".pem", ".key")

    mv.Field(cfg.AllowedIPs, "allowed_ips").
        ArrayNotEmpty()

    return mv.Validate()
}
Payment Processing / 결제 처리
type PaymentRequest struct {
    CardNumber string
    CardType   string
    CVV        string
    Amount     float64
    Currency   string
    Email      string
}

func ValidatePayment(req PaymentRequest) error {
    mv := validation.NewValidator()

    mv.Field(req.CardNumber, "card_number").
        Required().
        CreditCard()

    mv.Field(req.CardType, "card_type").
        Required().
        In("visa", "mastercard", "amex", "discover")

    mv.Field(req.CVV, "cvv").
        Required().
        Numeric().
        Length(3)  // or 4 for Amex

    mv.Field(req.Amount, "amount").
        Positive().
        Min(0.01).
        Max(999999.99)

    mv.Field(req.Currency, "currency").
        Required().
        Length(3).
        Uppercase().
        In("USD", "EUR", "GBP", "JPY", "KRW")

    mv.Field(req.Email, "email").
        Required().
        Email()

    return mv.Validate()
}

Error Handling / 에러 처리

err := mv.Validate()
if err != nil {
    // Type assertion to ValidationErrors
    // ValidationErrors로 타입 단언
    validationErrs := err.(validation.ValidationErrors)

    // Get all errors / 모든 에러 가져오기
    for _, e := range validationErrs {
        fmt.Printf("Field: %s, Rule: %s, Message: %s\n",
            e.Field, e.Rule, e.Message)
    }

    // Check specific field / 특정 필드 확인
    if validationErrs.HasField("email") {
        fmt.Println("Email validation failed")
    }

    // Get errors for specific field / 특정 필드의 에러 가져오기
    emailErrs := validationErrs.GetField("email")
    for _, e := range emailErrs {
        fmt.Println(e.Message)
    }

    // Get first error / 첫 번째 에러 가져오기
    firstErr := validationErrs.First()
    fmt.Println(firstErr.Message)

    // Get error count / 에러 개수 가져오기
    count := validationErrs.Count()
    fmt.Printf("Total errors: %d\n", count)

    // Convert to map for JSON response / JSON 응답을 위해 맵으로 변환
    errMap := validationErrs.ToMap()
    // Returns: {"email": ["invalid format"], "age": ["must be positive"]}
}

Performance / 성능

  • Zero allocation for simple validations / 간단한 검증은 할당 없음
  • 🚀 Efficient regex caching / 효율적인 정규식 캐싱
  • 💾 Minimal reflection usage / 최소한의 reflection 사용
  • 99.4% test coverage / 99.4% 테스트 커버리지
  • 🔬 Comprehensive test suite: Unit, Benchmark, Fuzz, Property, Performance, Load, Stress, Security tests
Benchmark Results / 벤치마크 결과
BenchmarkSimpleValidation-8       10000000    105 ns/op    0 B/op    0 allocs/op
BenchmarkChainValidation-8         5000000    245 ns/op    0 B/op    0 allocs/op
BenchmarkMultiFieldValidation-8    1000000   1250 ns/op  128 B/op    3 allocs/op

Installation / 설치

go get github.com/arkd0ng/go-utils/validation

Requirements / 요구사항

  • Go 1.18 or higher (for generics support) / Go 1.18 이상 (제네릭 지원)

Documentation / 문서

  • User Manual - Comprehensive guide with examples / 예제가 있는 포괄적인 가이드
  • Developer Guide - Architecture and internals / 아키텍처와 내부 구조
  • Design Plan - Design decisions and rationale / 설계 결정과 근거
  • Examples - Executable examples / 실행 가능한 예제

Key Features / 주요 기능

🎯 Comprehensive Validation / 포괄적인 검증
  • 135+ built-in validators covering all common use cases
  • 17 categories of validators organized by domain
  • Bilingual error messages in English and Korean
⛓️ Fluent API / Fluent API
  • Method chaining for readable validation code
  • StopOnError for efficient validation
  • Custom messages at any point in the chain
🛡️ Type Safety / 타입 안전
  • Generic type support where applicable
  • Type assertions handled internally
  • Compile-time safety for common operations
🌐 i18n Support / 국제화 지원
  • Built-in bilingual messages (English/Korean)
  • Custom message override for any validator
  • Easy to extend to other languages
🚀 Production Ready / 프로덕션 준비 완료
  • 99.4% test coverage with 533 test functions
  • Enterprise-grade quality with comprehensive test types
  • Zero external dependencies for maximum compatibility
  • Well-documented with extensive examples

Version History / 버전 히스토리

  • v1.13.035 (Current) - Enhanced documentation with all 135+ validators
  • v1.13.034 - Achieved 99.4% test coverage
  • v1.13.033 - Added Performance, Load, Stress, Security tests
  • v1.13.032 - Added Fuzz and Property-based tests
  • v1.13.031 - Added custom error message pre-configuration
  • v1.13.030 - Documentation updates

Statistics / 통계

  • Total Validators: 135+
  • Total Categories: 17
  • Test Coverage: 99.4%
  • Test Functions: 533
  • Lines of Code: ~10,000+
  • Lines of Tests: ~15,000+
  • Documentation: Bilingual (EN/KR)

License / 라이선스

MIT License

Contributing / 기여

Contributions are welcome! Please feel free to submit a Pull Request.

기여를 환영합니다! Pull Request를 자유롭게 제출해주세요.

Author / 작성자

arkd0ng - GitHub


Built with ❤️ for Go developers / Go 개발자를 위해 ❤️로 제작

Star ⭐ this repo if you find it useful! / 유용하다면 이 저장소에 별표 ⭐를 눌러주세요!

Documentation

Overview

Package validation provides comprehensive data validation utilities for Go applications. It offers a fluent, chainable API for validating strings, numbers, collections, dates, files, networks, and business logic with extensive built-in rules.

validation 패키지는 Go 애플리케이션을 위한 포괄적인 데이터 검증 유틸리티를 제공합니다. 문자열, 숫자, 컬렉션, 날짜, 파일, 네트워크 및 비즈니스 로직을 광범위한 내장 규칙으로 검증하기 위한 유창하고 체이닝 가능한 API를 제공합니다.

Key Features / 주요 기능:

  • Fluent chainable API for readable validation logic 읽기 쉬운 검증 로직을 위한 유창한 체이닝 API

  • 100+ built-in validation rules covering common use cases 일반적인 사용 사례를 다루는 100개 이상의 내장 검증 규칙

  • Support for strings, numbers, arrays, maps, dates, files, and more 문자열, 숫자, 배열, 맵, 날짜, 파일 등 지원

  • Bilingual error messages (English/Korean) 이중 언어 에러 메시지 (영문/한글)

  • Custom validation rules and error messages 사용자 정의 검증 규칙 및 에러 메시지

  • Field-level and multi-field validation support 필드 레벨 및 다중 필드 검증 지원

  • Stop-on-first-error or collect-all-errors modes 첫 에러에서 중단 또는 모든 에러 수집 모드

Validation Categories / 검증 카테고리:

String Validation (rules_string.go):

  • Length, format, content validation
  • Pattern matching with regex support
  • Case-insensitive comparisons
  • Unicode and multibyte character support

Numeric Validation (rules_numeric.go):

  • Range validation (min, max, between)
  • Type validation (positive, negative, zero)
  • Multiple data type support (int, float, string numbers)

Collection Validation (rules_collection.go):

  • Array/slice validation (length, uniqueness, containment)
  • Map validation (keys, values, size)
  • Empty/non-empty checks

Date/Time Validation (rules_datetime.go):

  • Date comparison (before, after, equal)
  • Date range validation
  • Format validation
  • Timezone-aware comparisons

File Validation (rules_file.go):

  • Path validation
  • Existence, readability, writability checks
  • File size and extension validation

Network Validation (rules_network.go):

  • Email, URL, IP address validation
  • Domain name validation
  • Port number validation
  • MAC address validation

Format Validation (rules_format.go):

  • JSON, XML, Base64 validation
  • UUID, ISBN validation
  • Phone number, postal code validation

Business Logic (rules_business.go):

  • Credit card validation with Luhn algorithm
  • Tax ID validation (SSN, EIN)
  • Currency validation

Type Validation (rules_type.go):

  • Type checking (string, number, boolean, array, etc.)
  • Nil/empty validation
  • Type conversion validation

Performance / 성능:

  • Zero memory allocation for simple validations 간단한 검증의 경우 메모리 할당 없음

  • Lazy evaluation with short-circuit on StopOnError StopOnError 시 단락 평가를 통한 지연 평가

  • Efficient regex compilation and caching 효율적인 정규식 컴파일 및 캐싱

  • Thread-safe: All validators are safe for concurrent use 스레드 안전: 모든 검증기는 동시 사용 안전

Thread Safety / 스레드 안전성:

All validation functions are thread-safe and can be used concurrently. Each Validator instance maintains its own state and does not share data.

모든 검증 함수는 스레드 안전하며 동시에 사용할 수 있습니다. 각 Validator 인스턴스는 자체 상태를 유지하며 데이터를 공유하지 않습니다.

Quick Start / 빠른 시작:

Basic single field validation:

// String validation / 문자열 검증
v := validation.New("test@example.com", "email")
v.Required().Email()
if err := v.Validate(); err != nil {
    // Handle validation errors / 검증 에러 처리
}

// Numeric validation / 숫자 검증
v := validation.New(25, "age")
v.Required().Min(18).Max(100)
if err := v.Validate(); err != nil {
    // Handle errors / 에러 처리
}

Chaining multiple rules:

v := validation.New(username, "username")
v.Required().
  MinLength(3).
  MaxLength(20).
  AlphaNumeric().
  NoWhitespace()

if err := v.Validate(); err != nil {
    // Validation failed / 검증 실패
}

Custom error messages:

v := validation.New(email, "email")
v.Required().WithMessage("Email is required / 이메일은 필수입니다").
  Email().WithMessage("Invalid email format / 유효하지 않은 이메일 형식")

Stop on first error:

v := validation.New(value, "field").StopOnError()
v.Required().MinLength(5).MaxLength(10)
// Stops at first failed rule / 첫 번째 실패한 규칙에서 중단

Multi-field validation:

mv := validation.NewValidator()
mv.Field(username, "username").Required().MinLength(3)
mv.Field(email, "email").Required().Email()
mv.Field(age, "age").Required().Min(18)

if err := mv.Validate(); err != nil {
    // Handle errors for all fields / 모든 필드의 에러 처리
}

Custom validation rules:

v := validation.New(value, "field")
v.Custom(func(val interface{}) bool {
    // Custom validation logic / 사용자 정의 검증 로직
    return val.(string) != "forbidden"
}).WithMessage("Value is forbidden / 금지된 값입니다")

Error Handling / 에러 처리:

The package provides detailed error information including:

  • Field name that failed validation / 검증 실패한 필드 이름
  • Failed validation rule / 실패한 검증 규칙
  • Actual value that failed / 실패한 실제 값
  • Descriptive error message / 설명적인 에러 메시지

Example error handling:

if err := v.Validate(); err != nil {
    if validationErrors, ok := err.(validation.ValidationErrors); ok {
        for _, e := range validationErrors {
            fmt.Printf("Field: %s, Rule: %s, Message: %s\n",
                e.Field, e.Rule, e.Message)
        }
    }
}

Common Patterns / 일반적인 패턴:

User registration validation:

validator := validation.NewValidator()
validator.Field(user.Email, "email").
    Required().
    Email().
    MaxLength(100)
validator.Field(user.Password, "password").
    Required().
    MinLength(8).
    ContainsDigit().
    ContainsSpecialChar()
validator.Field(user.Age, "age").
    Required().
    Min(18).
    Max(120)

API request validation:

v := validation.New(request.Data, "data").StopOnError()
v.Required().Type("array").ArrayNotEmpty()
if err := v.Validate(); err != nil {
    return BadRequestError(err)
}

File upload validation:

v := validation.New(filepath, "upload")
v.Required().
  FileExists().
  FileReadable().
  FileSize(0, 10*1024*1024).  // Max 10MB
  FileExtension(".jpg", ".png", ".gif")

Best Practices / 모범 사례:

  1. Use descriptive field names for better error messages 더 나은 에러 메시지를 위해 설명적인 필드 이름 사용

  2. Chain related rules together for readability 가독성을 위해 관련 규칙을 함께 체이닝

  3. Use StopOnError() for expensive validations 비용이 많이 드는 검증에는 StopOnError() 사용

  4. Provide custom messages for business-specific rules 비즈니스별 규칙에 사용자 정의 메시지 제공

  5. Validate early in your request handlers 요청 핸들러에서 조기에 검증

  6. Reuse validation logic across similar use cases 유사한 사용 사례에서 검증 로직 재사용

See also / 참고:

  • errors.go: Error types and handling / 에러 타입 및 처리
  • types.go: Core types and interfaces / 핵심 타입 및 인터페이스
  • rules_*.go: Specific validation rule implementations / 특정 검증 규칙 구현

Version: 1.13.x Author: arkd0ng License: MIT

Example (BusinessIDValidation)

Example_businessIDValidation demonstrates business ID validation Example_businessIDValidation는 비즈니스 ID 검증을 보여줍니다

package main

import (
	"fmt"

	"github.com/arkd0ng/go-utils/validation"
)

func main() {
	mv := validation.NewValidator()

	// Validate book ISBN
	mv.Field("978-0-596-52068-7", "book_isbn").ISBN()

	// Validate journal ISSN
	mv.Field("2049-3630", "journal_issn").ISSN()

	// Validate product EAN
	mv.Field("4006381333931", "product_ean").EAN()

	err := mv.Validate()
	if err != nil {
		fmt.Println("Invalid IDs")
	} else {
		fmt.Println("All IDs valid")
	}
}
Output:

All IDs valid
Example (ChainedValidation)

Example_chainedValidation demonstrates chaining multiple validators Example_chainedValidation는 여러 검증기 체이닝을 보여줍니다

package main

import (
	"fmt"

	"github.com/arkd0ng/go-utils/validation"
)

func main() {
	v := validation.New("user@example.com", "email")
	v.Required().MinLength(5).MaxLength(100).Email()

	err := v.Validate()
	if err != nil {
		fmt.Println("Validation failed")
	} else {
		fmt.Println("Email is valid")
	}
}
Output:

Email is valid
Example (ColorValidation)

Example_colorValidation demonstrates color validation Example_colorValidation는 색상 검증을 보여줍니다

package main

import (
	"fmt"

	"github.com/arkd0ng/go-utils/validation"
)

func main() {
	mv := validation.NewValidator()

	// Validate hex color
	mv.Field("#FF5733", "primary_color").HexColor()

	// Validate RGB color
	mv.Field("rgb(255, 87, 51)", "secondary_color").RGB()

	// Validate RGBA color
	mv.Field("rgba(255, 87, 51, 0.8)", "overlay_color").RGBA()

	// Validate HSL color
	mv.Field("hsl(9, 100%, 60%)", "accent_color").HSL()

	err := mv.Validate()
	if err != nil {
		fmt.Println("Invalid colors")
	} else {
		fmt.Println("All colors valid")
	}
}
Output:

All colors valid
Example (ComplexValidation)

Example_complexValidation demonstrates complex validation scenario Example_complexValidation는 복잡한 검증 시나리오를 보여줍니다

package main

import (
	"fmt"

	"github.com/arkd0ng/go-utils/validation"
)

func main() {
	// User registration validation
	mv := validation.NewValidator()

	// Username validation
	mv.Field("john_doe", "username").
		Required().
		MinLength(3).
		MaxLength(50)

	// Password validation
	mv.Field("SecurePass123!", "password").
		Required().
		MinLength(8).
		MaxLength(128)

	// Age validation
	mv.Field(25, "age").
		Min(18).
		Max(150)

	// Role validation
	mv.Field("user", "role").
		Required().
		In("admin", "user", "moderator")

	err := mv.Validate()
	if err != nil {
		fmt.Println("Registration validation failed")
	} else {
		fmt.Println("Registration data is valid")
	}
}
Output:

Registration data is valid
Example (CreditCardTypeValidation)

Example_creditCardTypeValidation demonstrates validation of different card types Example_creditCardTypeValidation는 다양한 카드 타입 검증을 보여줍니다

package main

import (
	"fmt"

	"github.com/arkd0ng/go-utils/validation"
)

func main() {
	mv := validation.NewValidator()

	// Validate Visa
	mv.Field("4532015112830366", "visa_card").CreditCardType("visa")

	// Validate Mastercard
	mv.Field("5425233430109903", "mastercard").CreditCardType("mastercard")

	// Validate Amex
	mv.Field("374245455400126", "amex_card").CreditCardType("amex")

	err := mv.Validate()
	if err != nil {
		fmt.Println("Invalid cards")
	} else {
		fmt.Println("All cards valid")
	}
}
Output:

All cards valid
Example (CreditCardValidation)

Example_creditCardValidation demonstrates credit card validation with spaces and hyphens Example_creditCardValidation는 공백과 하이픈이 있는 신용카드 검증을 보여줍니다

package main

import (
	"fmt"

	"github.com/arkd0ng/go-utils/validation"
)

func main() {
	// Credit card with spaces
	v := validation.New("4532 0151 1283 0366", "card_number")
	v.CreditCard()

	if len(v.GetErrors()) > 0 {
		fmt.Println("Invalid")
	} else {
		fmt.Println("Valid with spaces")
	}
}
Output:

Valid with spaces
Example (DataFormatValidation)

Example_dataFormatValidation demonstrates multiple data format validators. Example_dataFormatValidation는 여러 데이터 형식 검증기를 보여줍니다.

package main

import (
	"fmt"

	"github.com/arkd0ng/go-utils/validation"
)

func main() {
	mv := validation.NewValidator()

	// Validate ASCII text
	mv.Field("Hello World", "ascii_text").ASCII()

	// Validate printable text (no control characters)
	mv.Field("Display Text!", "display_text").Printable()

	// Validate whitespace
	mv.Field("   ", "spacing").Whitespace()

	// Validate name with spaces
	mv.Field("John Doe", "full_name").AlphaSpace()

	err := mv.Validate()
	if err != nil {
		fmt.Println("Invalid data")
	} else {
		fmt.Println("All data valid")
	}
}
Output:

All data valid
Example (DateTimeValidation)

Example_dateTimeValidation demonstrates comprehensive date/time validation Example_dateTimeValidation는 포괄적인 날짜/시간 검증을 보여줍니다

package main

import (
	"fmt"
	"time"

	"github.com/arkd0ng/go-utils/validation"
)

func main() {
	// Event scheduling validation
	minDate := time.Date(2025, 1, 1, 0, 0, 0, 0, time.UTC)
	maxDate := time.Date(2025, 12, 31, 23, 59, 59, 0, time.UTC)
	eventDateTime := time.Date(2025, 10, 17, 14, 30, 0, 0, time.UTC)

	mv := validation.NewValidator()
	mv.Field("2025-10-17", "event_date").Required().DateFormat("2006-01-02")
	mv.Field("14:30:00", "event_time").Required().TimeFormat("15:04:05")
	mv.Field(eventDateTime, "event_datetime").DateAfter(minDate).DateBefore(maxDate)

	err := mv.Validate()
	if err != nil {
		fmt.Println("Invalid event schedule")
	} else {
		fmt.Println("Valid event schedule")
	}
}
Output:

Valid event schedule
Example (FileExistsValidation)

Example_fileExistsValidation demonstrates file existence validation Example_fileExistsValidation은 파일 존재 검증을 보여줍니다

package main

import (
	"fmt"
	"os"

	"github.com/arkd0ng/go-utils/validation"
)

func main() {
	// Create a temporary file for demonstration
	tmpFile, _ := os.CreateTemp("", "example_*.txt")
	tmpFile.Close()
	defer os.Remove(tmpFile.Name())

	v := validation.New(tmpFile.Name(), "log_file")
	v.FileExists()

	err := v.Validate()
	if err != nil {
		fmt.Println("File does not exist")
	} else {
		fmt.Println("File exists")
	}
}
Output:

File exists
Example (FileExtensionValidation)

Example_fileExtensionValidation demonstrates file extension validation Example_fileExtensionValidation은 파일 확장자 검증을 보여줍니다

package main

import (
	"fmt"

	"github.com/arkd0ng/go-utils/validation"
)

func main() {
	v := validation.New("document.pdf", "file_name")
	v.FileExtension(".pdf", ".doc", ".docx")

	err := v.Validate()
	if err != nil {
		fmt.Println("Invalid file extension")
	} else {
		fmt.Println("Valid file extension")
	}
}
Output:

Valid file extension
Example (FilePathValidation)

Example_filePathValidation demonstrates file path validation Example_filePathValidation은 파일 경로 검증을 보여줍니다

package main

import (
	"fmt"

	"github.com/arkd0ng/go-utils/validation"
)

func main() {
	v := validation.New("./config/app.json", "config_file")
	v.FilePath()

	err := v.Validate()
	if err != nil {
		fmt.Println("Invalid file path")
	} else {
		fmt.Println("Valid file path")
	}
}
Output:

Valid file path
Example (FileSizeValidation)

Example_fileSizeValidation demonstrates file size validation Example_fileSizeValidation은 파일 크기 검증을 보여줍니다

package main

import (
	"fmt"
	"os"

	"github.com/arkd0ng/go-utils/validation"
)

func main() {
	// Create a temporary file with content
	tmpFile, _ := os.CreateTemp("", "example_*.txt")
	tmpFile.WriteString("Hello, World!")
	tmpFile.Close()
	defer os.Remove(tmpFile.Name())

	v := validation.New(tmpFile.Name(), "upload_file")
	v.FileSize(0, 1024) // Max 1KB

	err := v.Validate()
	if err != nil {
		fmt.Println("File size out of range")
	} else {
		fmt.Println("File size OK")
	}
}
Output:

File size OK
Example (FileValidationComprehensive)

Example_fileValidationComprehensive demonstrates comprehensive file validation Example_fileValidationComprehensive는 포괄적인 파일 검증을 보여줍니다

package main

import (
	"fmt"
	"os"

	"github.com/arkd0ng/go-utils/validation"
)

func main() {
	// Create a temporary file for demonstration
	tmpFile, _ := os.CreateTemp("", "upload_*.txt")
	tmpFile.WriteString("Test content")
	tmpFile.Close()
	defer os.Remove(tmpFile.Name())

	mv := validation.NewValidator()
	mv.Field(tmpFile.Name(), "upload_file").
		FileExists().
		FileReadable().
		FileSize(0, 10240). // Max 10KB
		FileExtension(".txt", ".log")

	err := mv.Validate()
	if err != nil {
		fmt.Println("Invalid file")
	} else {
		fmt.Println("Valid file")
	}
}
Output:

Valid file
Example (FormatValidationComprehensive)

Example_formatValidationComprehensive demonstrates comprehensive format validation Example_formatValidationComprehensive는 포괄적인 형식 검증을 보여줍니다

package main

import (
	"fmt"

	"github.com/arkd0ng/go-utils/validation"
)

func main() {
	// API Request validation with multiple format checks
	requestID := "550e8400-e29b-41d4-a716-446655440000"
	configData := `{"timeout": 30, "retries": 3}`
	hexToken := "0xabcd1234"

	mv := validation.NewValidator()
	mv.Field(requestID, "request_id").UUIDv4()
	mv.Field(configData, "config").JSON()
	mv.Field(hexToken, "token").Hex()

	err := mv.Validate()
	if err != nil {
		fmt.Println("Invalid request format")
	} else {
		fmt.Println("Valid request format")
	}
}
Output:

Valid request format
Example (GeographicValidation)

Example_geographicValidation demonstrates geographic validation Example_geographicValidation는 지리적 검증을 보여줍니다

package main

import (
	"fmt"

	"github.com/arkd0ng/go-utils/validation"
)

func main() {
	mv := validation.NewValidator()

	// Validate latitude
	mv.Field(37.5665, "latitude").Latitude()

	// Validate longitude
	mv.Field(126.9780, "longitude").Longitude()

	// Validate coordinate string
	mv.Field("40.7128,-74.0060", "nyc_location").Coordinate()

	err := mv.Validate()
	if err != nil {
		fmt.Println("Invalid location")
	} else {
		fmt.Println("All locations valid")
	}
}
Output:

All locations valid
Example (HexValidation)

Example_hexValidation demonstrates hexadecimal validation Example_hexValidation은 16진수 검증을 보여줍니다

package main

import (
	"fmt"

	"github.com/arkd0ng/go-utils/validation"
)

func main() {
	v := validation.New("0xdeadbeef", "color_code")
	v.Hex()

	err := v.Validate()
	if err != nil {
		fmt.Println("Invalid hex")
	} else {
		fmt.Println("Valid hex")
	}
}
Output:

Valid hex
Example (LogicalValidation)

Example_logicalValidation demonstrates multiple logical validators. Example_logicalValidation는 여러 논리 검증기를 보여줍니다.

package main

import (
	"fmt"

	"github.com/arkd0ng/go-utils/validation"
)

func main() {
	mv := validation.NewValidator()

	// Validate status is one of allowed values
	mv.Field("active", "status").OneOf("active", "inactive", "pending")

	// Validate username is not forbidden
	mv.Field("user123", "username").NotOneOf("admin", "root")

	// Conditional validation
	isProduction := true
	mv.Field("prod-server", "server").When(isProduction, func(val *validation.Validator) {
		val.Required().MinLength(5)
	})

	// Inverse conditional validation
	isTestMode := false
	mv.Field("test@example.com", "email").Unless(isTestMode, func(val *validation.Validator) {
		val.Required().Email()
	})

	err := mv.Validate()
	if err != nil {
		fmt.Println("Invalid data")
	} else {
		fmt.Println("All validations passed")
	}
}
Output:

All validations passed
Example (NetworkValidation)

Example_networkValidation demonstrates validating network configuration Example_networkValidation는 네트워크 구성 검증을 보여줍니다

package main

import (
	"fmt"

	"github.com/arkd0ng/go-utils/validation"
)

func main() {
	// Validate server configuration
	mv := validation.NewValidator()
	mv.Field("192.168.1.10", "server_ip").Required().IPv4()
	mv.Field("192.168.1.0/24", "subnet").Required().CIDR()
	mv.Field("00:1A:2B:3C:4D:5E", "mac").Required().MAC()

	err := mv.Validate()
	if err != nil {
		fmt.Println("Invalid network configuration")
	} else {
		fmt.Println("Valid network configuration")
	}
}
Output:

Valid network configuration
Example (RangeValidation)

Example_rangeValidation demonstrates using Min and Max together for range validation Example_rangeValidation는 범위 검증을 위해 Min과 Max를 함께 사용하는 것을 보여줍니다

package main

import (
	"fmt"

	"github.com/arkd0ng/go-utils/validation"
)

func main() {
	v := validation.New(50, "percentage")
	v.Min(0).Max(100)
	err := v.Validate()
	if err != nil {
		fmt.Println("Out of range")
	} else {
		fmt.Println("Valid percentage")
	}
}
Output:

Valid percentage
Example (RangeValidationComprehensive)

Example_rangeValidationComprehensive demonstrates comprehensive range validation Example_rangeValidationComprehensive는 포괄적인 범위 검증을 보여줍니다

package main

import (
	"fmt"
	"time"

	"github.com/arkd0ng/go-utils/validation"
)

func main() {
	// Event validation with multiple range checks
	start := time.Date(2025, 1, 1, 0, 0, 0, 0, time.UTC)
	end := time.Date(2025, 12, 31, 23, 59, 59, 0, time.UTC)
	eventDate := time.Date(2025, 6, 15, 12, 0, 0, 0, time.UTC)

	mv := validation.NewValidator()
	mv.Field(25, "participant_age").IntRange(18, 65)
	mv.Field(25.50, "ticket_price").FloatRange(10.0, 100.0)
	mv.Field(eventDate, "event_date").DateRange(start, end)

	err := mv.Validate()
	if err != nil {
		fmt.Println("Invalid event data")
	} else {
		fmt.Println("Valid event data")
	}
}
Output:

Valid event data
Example (SecurityValidation)

Example_securityValidation demonstrates security validation Example_securityValidation는 보안 검증을 보여줍니다

package main

import (
	"fmt"

	"github.com/arkd0ng/go-utils/validation"
)

func main() {
	mv := validation.NewValidator()

	// Validate JWT token
	mv.Field("eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIn0.dozjgNryP4J3jVmNHl0w5N_XgL0n3I9PlFUP0THsR8U", "token").JWT()

	// Validate BCrypt password hash
	mv.Field("$2a$10$N9qo8uLOickgx2ZMRZoMyeIjZAgcfl7p92ldGxad68LJZdL17lhWy", "password").BCrypt()

	// Validate file hash
	mv.Field("e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", "file_hash").SHA256()

	err := mv.Validate()
	if err != nil {
		fmt.Println("Invalid security data")
	} else {
		fmt.Println("All security data valid")
	}
}
Output:

All security data valid
Example (Uuidv4Validation)

Example_uuidv4Validation demonstrates UUIDv4 validation Example_uuidv4Validation은 UUIDv4 검증을 보여줍니다

package main

import (
	"fmt"

	"github.com/arkd0ng/go-utils/validation"
)

func main() {
	v := validation.New("550e8400-e29b-41d4-a716-446655440000", "request_id")
	v.UUIDv4()

	err := v.Validate()
	if err != nil {
		fmt.Println("Invalid UUID v4")
	} else {
		fmt.Println("Valid UUID v4")
	}
}
Output:

Valid UUID v4
Example (XmlValidation)

Example_xmlValidation demonstrates XML validation Example_xmlValidation은 XML 검증을 보여줍니다

package main

import (
	"fmt"

	"github.com/arkd0ng/go-utils/validation"
)

func main() {
	xmlData := `<?xml version="1.0"?>
	<person>
		<name>John Doe</name>
		<age>30</age>
	</person>`

	v := validation.New(xmlData, "user_data")
	v.XML()

	err := v.Validate()
	if err != nil {
		fmt.Println("Invalid XML")
	} else {
		fmt.Println("Valid XML")
	}
}
Output:

Valid XML

Index

Examples

Constants

This section is empty.

Variables

View Source
var Version = version.Get()

Version returns the current package version string from cfg/app.yaml. It provides the semantic version number for the validation package.

Version은 cfg/app.yaml에서 현재 패키지 버전 문자열을 반환합니다. validation 패키지의 시맨틱 버전 번호를 제공합니다.

Format / 형식:

  • Semantic versioning: "v1.13.x" 시맨틱 버저닝: "v1.13.x"

Usage / 사용법:

version := validation.Version
fmt.Printf("Validation package version: %s\n", version)

Thread Safety / 스레드 안전성:

  • Thread-safe: Read-only variable 스레드 안전: 읽기 전용 변수

Functions

This section is empty.

Types

type MessageFunc

type MessageFunc func(field string, value interface{}) string

MessageFunc is a function type for generating custom error messages. It receives field name and value, returning a custom error message.

MessageFunc는 사용자 정의 에러 메시지를 생성하기 위한 함수 타입입니다. 필드 이름과 값을 받아 사용자 정의 에러 메시지를 반환합니다.

Parameters / 매개변수:

  • field: Name of the field that failed validation 검증 실패한 필드 이름
  • value: The actual value that failed validation 검증 실패한 실제 값

Returns / 반환값:

  • string: Custom error message 사용자 정의 에러 메시지

Usage / 사용법:

  • Used for dynamic error message generation 동적 에러 메시지 생성에 사용
  • Allows context-aware error messages 컨텍스트 인식 에러 메시지 허용
  • Can include field value in message 메시지에 필드 값 포함 가능

Example / 예제:

msgFunc := func(field string, value interface{}) string {
    return fmt.Sprintf("Field '%s' with value '%v' is invalid", field, value)
}

// Use with custom validation / 사용자 정의 검증과 함께 사용
v := validation.New(data, "field")
v.Custom(customRule).WithMessage(msgFunc("field", data))

type MultiValidator

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

MultiValidator represents a validator for multiple fields. It allows validation of multiple fields with independent error collection per field.

MultiValidator는 여러 필드에 대한 검증기를 나타냅니다. 필드별 독립적인 에러 컬렉션으로 여러 필드의 검증을 허용합니다.

Use Cases / 사용 사례:

  • Form validation with multiple inputs 여러 입력이 있는 폼 검증
  • API request validation with multiple parameters 여러 매개변수가 있는 API 요청 검증
  • Complex object validation with nested fields 중첩 필드가 있는 복잡한 객체 검증
  • Batch validation of related fields 관련 필드의 배치 검증

Thread Safety / 스레드 안전성:

  • Not safe for concurrent use 동시 사용 안전하지 않음
  • Create separate instances for concurrent validation 동시 검증을 위해 별도 인스턴스 생성

Example / 예제:

mv := validation.NewValidator()
mv.Field(user.Email, "email").Required().Email()
mv.Field(user.Age, "age").Required().Min(18).Max(120)
mv.Field(user.Name, "name").Required().MinLength(2)

if err := mv.Validate(); err != nil {
    // All field errors collected / 모든 필드 에러 수집됨
}

func NewValidator

func NewValidator() *MultiValidator

NewValidator creates a new MultiValidator for multiple fields. NewValidator는 여러 필드를 위한 새 MultiValidator를 생성합니다.

Example

ExampleNewValidator demonstrates MultiValidator for multiple fields ExampleNewValidator는 여러 필드를 위한 MultiValidator를 보여줍니다

package main

import (
	"fmt"

	"github.com/arkd0ng/go-utils/validation"
)

func main() {
	mv := validation.NewValidator()
	mv.Field("john", "name").Required().MinLength(2)
	mv.Field(25, "age").Min(18).Max(150)

	err := mv.Validate()
	if err != nil {
		fmt.Println("Validation failed")
	} else {
		fmt.Println("All fields valid")
	}
}
Output:

All fields valid

func (*MultiValidator) Field

func (mv *MultiValidator) Field(value interface{}, fieldName string) *Validator

Field adds a field to the multi-validator and returns a Validator for chaining. Field는 multi-validator에 필드를 추가하고 체이닝을 위한 Validator를 반환합니다.

Example

ExampleMultiValidator_Field demonstrates adding fields to MultiValidator ExampleMultiValidator_Field는 MultiValidator에 필드 추가를 보여줍니다

package main

import (
	"fmt"

	"github.com/arkd0ng/go-utils/validation"
)

func main() {
	mv := validation.NewValidator()
	mv.Field("TestUser", "username").Required().MinLength(3)
	mv.Field(100, "score").Min(0).Max(200)

	err := mv.Validate()
	if err != nil {
		fmt.Println("Validation errors found")
	} else {
		fmt.Println("All validations passed")
	}
}
Output:

All validations passed

func (*MultiValidator) GetErrors

func (mv *MultiValidator) GetErrors() []ValidationError

GetErrors returns all validation errors from all fields. GetErrors는 모든 필드의 모든 검증 에러를 반환합니다.

func (*MultiValidator) Validate

func (mv *MultiValidator) Validate() error

Validate executes all validators and returns an error if any fail. Validate는 모든 검증기를 실행하고, 실패 시 에러를 반환합니다.

type RuleFunc

type RuleFunc func(interface{}) bool

RuleFunc is a function type for custom validation rules. It receives a value and returns true if valid, false otherwise.

RuleFunc는 사용자 정의 검증 규칙을 위한 함수 타입입니다. 값을 받아 유효하면 true, 아니면 false를 반환합니다.

Parameters / 매개변수:

  • interface{}: Value to validate (can be any type) 검증할 값 (모든 타입 가능)

Returns / 반환값:

  • bool: true if validation passes, false if fails 검증 통과 시 true, 실패 시 false

Usage / 사용법:

  • Used with Custom() method for business-specific validation 비즈니스별 검증을 위해 Custom() 메서드와 함께 사용
  • Should perform type assertion if specific type expected 특정 타입이 예상되는 경우 타입 단언 수행해야 함
  • Should return false for unexpected types 예상치 못한 타입에 대해 false 반환해야 함

Example / 예제:

// Simple custom rule / 간단한 사용자 정의 규칙
isPositive := func(val interface{}) bool {
    if num, ok := val.(int); ok {
        return num > 0
    }
    return false
}

v := validation.New(value, "number")
v.Custom(isPositive).WithMessage("Must be positive")

// Complex business rule / 복잡한 비즈니스 규칙
checkAvailability := func(val interface{}) bool {
    username := val.(string)
    return !db.UserExists(username)
}

v := validation.New(username, "username")
v.Custom(checkAvailability).WithMessage("Username already taken")

type ValidationError

type ValidationError struct {
	Field   string      // Field name / 필드 이름
	Value   interface{} // Invalid value / 유효하지 않은 값
	Rule    string      // Failed rule / 실패한 규칙
	Message string      // Error message / 에러 메시지
}

ValidationError represents a single validation error with detailed context. It contains all information needed to understand and handle a validation failure.

ValidationError는 상세한 컨텍스트를 포함한 단일 검증 에러를 나타냅니다. 검증 실패를 이해하고 처리하는 데 필요한 모든 정보를 포함합니다.

Fields / 필드:

  • Field: Name of the field that failed (e.g., "email", "age") 실패한 필드 이름 (예: "email", "age")
  • Value: The actual value that failed validation (any type) 검증 실패한 실제 값 (모든 타입)
  • Rule: Name of the failed validation rule (e.g., "required", "email") 실패한 검증 규칙 이름 (예: "required", "email")
  • Message: Human-readable error message (bilingual supported) 사람이 읽을 수 있는 에러 메시지 (이중 언어 지원)

Use Cases / 사용 사례:

  • API error responses with detailed field errors 상세한 필드 에러가 있는 API 에러 응답
  • Form validation feedback to users 사용자에게 폼 검증 피드백
  • Logging validation failures with context 컨텍스트와 함께 검증 실패 로깅
  • Conditional error handling based on field or rule 필드 또는 규칙 기반 조건부 에러 처리

Thread Safety / 스레드 안전성:

  • Immutable after creation 생성 후 불변
  • Safe to read concurrently 동시 읽기 안전

Example / 예제:

err := ValidationError{
    Field:   "email",
    Value:   "invalid-email",
    Rule:    "email",
    Message: "Invalid email format",
}

// Access error details / 에러 상세 정보 액세스
fmt.Printf("Field: %s\n", err.Field)
fmt.Printf("Rule: %s\n", err.Rule)
fmt.Printf("Message: %s\n", err.Error())

func (ValidationError) Error

func (ve ValidationError) Error() string

Error returns the error message for this validation error. It implements the error interface for standard Go error handling.

Error는 이 검증 에러에 대한 에러 메시지를 반환합니다. 표준 Go 에러 처리를 위해 error 인터페이스를 구현합니다.

Returns / 반환값:

  • string: Custom message if set, or default formatted message 설정된 경우 사용자 정의 메시지, 그렇지 않으면 기본 포맷된 메시지

Behavior / 동작:

  • Returns custom message if Message field is non-empty Message 필드가 비어있지 않으면 사용자 정의 메시지 반환
  • Returns default format: "{Rule} validation failed for field '{Field}'" 기본 형식 반환: "{규칙} validation failed for field '{필드}'"

Thread Safety / 스레드 안전성:

  • Thread-safe: Read-only operation 스레드 안전: 읽기 전용 작업

Example / 예제:

err := ValidationError{
    Field:   "age",
    Value:   -5,
    Rule:    "min",
    Message: "Age must be at least 0",
}
fmt.Println(err.Error())  // "Age must be at least 0"

// Without custom message / 사용자 정의 메시지 없이
err2 := ValidationError{
    Field: "email",
    Rule:  "required",
}
fmt.Println(err2.Error())  // "required validation failed for field 'email'"

type ValidationErrors

type ValidationErrors []ValidationError

ValidationErrors is a collection of validation errors. It implements the error interface and provides utility methods for error inspection.

ValidationErrors는 검증 에러의 모음입니다. error 인터페이스를 구현하고 에러 검사를 위한 유틸리티 메서드를 제공합니다.

Behavior / 동작:

  • Acts as a slice of ValidationError ValidationError의 슬라이스로 동작
  • Can be empty (no errors) 비어있을 수 있음 (에러 없음)
  • Provides formatted output of all errors 모든 에러의 포맷된 출력 제공

Use Cases / 사용 사례:

  • Collecting multiple field validation errors 여러 필드 검증 에러 수집
  • Returning comprehensive validation feedback 포괄적인 검증 피드백 반환
  • Filtering errors by field or rule 필드 또는 규칙별 에러 필터링
  • API error responses with multiple violations 여러 위반 사항이 있는 API 에러 응답

Thread Safety / 스레드 안전성:

  • Safe to read concurrently 동시 읽기 안전
  • Not safe to modify concurrently 동시 수정 안전하지 않음

Example / 예제:

errors := validation.ValidationErrors{
    {Field: "email", Rule: "required", Message: "Email is required"},
    {Field: "age", Rule: "min", Message: "Age must be at least 18"},
}

// Use as error / 에러로 사용
if len(errors) > 0 {
    return errors  // Implements error interface
}

// Iterate through errors / 에러 순회
for _, err := range errors {
    log.Printf("Field %s failed: %s", err.Field, err.Message)
}
Example

ExampleValidationErrors demonstrates handling validation errors ExampleValidationErrors는 검증 에러 처리를 보여줍니다

package main

import (
	"fmt"

	"github.com/arkd0ng/go-utils/validation"
)

func main() {
	v := validation.New("", "email")
	v.StopOnError() // Stop at first error
	v.Required()
	v.Email()

	err := v.Validate()
	if err != nil {
		verrs := err.(validation.ValidationErrors)
		for _, verr := range verrs {
			fmt.Printf("Field: %s, Rule: %s\n", verr.Field, verr.Rule)
		}
	}
}
Output:

Field: email, Rule: required

func (ValidationErrors) Count

func (ve ValidationErrors) Count() int

Count returns the number of validation errors. Count는 검증 에러의 개수를 반환합니다.

func (ValidationErrors) Error

func (ve ValidationErrors) Error() string

Error returns a formatted error message for all validation errors. Multiple errors are separated by semicolons for easy parsing.

Error는 모든 검증 에러에 대한 포맷된 에러 메시지를 반환합니다. 여러 에러는 쉬운 파싱을 위해 세미콜론으로 구분됩니다.

Returns / 반환값:

  • string: Semicolon-separated error messages, or empty string if no errors 세미콜론으로 구분된 에러 메시지, 에러가 없으면 빈 문자열

Format / 형식:

  • Single error: "error message" 단일 에러: "에러 메시지"
  • Multiple errors: "error1; error2; error3" 여러 에러: "에러1; 에러2; 에러3"
  • No errors: "" 에러 없음: ""

Thread Safety / 스레드 안전성:

  • Thread-safe: Read-only operation 스레드 안전: 읽기 전용 작업

Performance / 성능:

  • Time complexity: O(n) where n is number of errors 시간 복잡도: O(n) (n은 에러 개수)
  • Memory allocation: One string allocation for join 메모리 할당: join을 위한 문자열 할당 1회

Example / 예제:

errors := validation.ValidationErrors{
    {Field: "email", Rule: "required", Message: "Email is required"},
    {Field: "age", Rule: "min", Message: "Age too low"},
}

msg := errors.Error()
// "Email is required; Age too low"

// Empty errors / 빈 에러
empty := validation.ValidationErrors{}
fmt.Println(empty.Error())  // ""

func (ValidationErrors) First

func (ve ValidationErrors) First() *ValidationError

First returns the first validation error, or nil if there are no errors. First는 첫 번째 검증 에러를 반환하거나, 에러가 없으면 nil을 반환합니다.

func (ValidationErrors) GetField

func (ve ValidationErrors) GetField(field string) []ValidationError

GetField returns all errors for a specific field. GetField는 특정 필드에 대한 모든 에러를 반환합니다.

func (ValidationErrors) HasField

func (ve ValidationErrors) HasField(field string) bool

HasField checks if there are errors for a specific field. HasField는 특정 필드에 대한 에러가 있는지 확인합니다.

func (ValidationErrors) ToMap

func (ve ValidationErrors) ToMap() map[string][]string

ToMap converts validation errors to a map of field names to error messages. ToMap은 검증 에러를 필드 이름과 에러 메시지의 맵으로 변환합니다.

type Validator

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

Validator represents a validation chain for a single value. It maintains validation state, error collection, and configuration for a field.

Validator는 단일 값에 대한 검증 체인을 나타냅니다. 필드에 대한 검증 상태, 에러 컬렉션 및 구성을 유지합니다.

Lifecycle / 생명주기:

  1. Creation: Use New() to create a new validator instance 생성: New()를 사용하여 새 검증기 인스턴스 생성
  2. Rule Chaining: Chain validation rules using fluent API 규칙 체이닝: 유창한 API를 사용하여 검증 규칙 체이닝
  3. Execution: Rules execute immediately when called 실행: 호출 시 규칙이 즉시 실행
  4. Result: Call Validate() or GetErrors() to retrieve results 결과: Validate() 또는 GetErrors()를 호출하여 결과 검색

State Management / 상태 관리:

  • Each validator maintains independent state 각 검증기는 독립적인 상태 유지
  • Errors accumulate unless StopOnError is set StopOnError가 설정되지 않으면 에러 누적
  • Custom messages can override default error messages 사용자 정의 메시지로 기본 에러 메시지 재정의 가능

Thread Safety / 스레드 안전성:

  • Not safe for concurrent modification 동시 수정 안전하지 않음
  • Safe to create multiple validators concurrently 여러 검증기를 동시에 생성하는 것은 안전
  • Do not share validator instances across goroutines 고루틴 간 검증기 인스턴스 공유하지 말 것

Memory / 메모리:

  • Small memory footprint (~100 bytes + error collection) 작은 메모리 공간 (~100바이트 + 에러 컬렉션)
  • Error collection grows with failed validations 에러 컬렉션은 실패한 검증과 함께 증가
  • Can be reused after calling Validate() Validate() 호출 후 재사용 가능

Example / 예제:

// Create and use validator / 검증기 생성 및 사용
v := validation.New("test@example.com", "email")
v.Required().Email().MaxLength(100)

if err := v.Validate(); err != nil {
    // Handle validation failure / 검증 실패 처리
}

// With custom configuration / 사용자 정의 구성과 함께
v := validation.New(data, "data").StopOnError()
v.Required().WithMessage("Data is required")

func New

func New(value interface{}, fieldName string) *Validator

New creates a new Validator for the given value and field name. It initializes a validator instance with empty error collection and default settings.

New는 주어진 값과 필드 이름에 대한 새 Validator를 생성합니다. 빈 에러 컬렉션과 기본 설정으로 검증기 인스턴스를 초기화합니다.

Parameters / 매개변수:

  • value: The value to be validated (can be any type including nil) 검증할 값 (nil을 포함한 모든 타입 가능)
  • fieldName: Name of the field for error messages (should be descriptive) 에러 메시지용 필드 이름 (설명적이어야 함)

Returns / 반환값:

  • *Validator: A new validator instance ready for rule chaining 규칙 체이닝 준비가 된 새 검증기 인스턴스

Behavior / 동작:

  • Creates validator with stopOnError=false (collects all errors by default) stopOnError=false로 검증기 생성 (기본적으로 모든 에러 수집)
  • Initializes empty error collection 빈 에러 컬렉션 초기화
  • Allocates custom message map 사용자 정의 메시지 맵 할당

Thread Safety / 스레드 안전성:

  • Thread-safe: Each call creates a new independent instance 스레드 안전: 각 호출은 새로운 독립 인스턴스 생성

Performance / 성능:

  • Time complexity: O(1) 시간 복잡도: O(1)
  • Memory allocation: One validator struct + empty slice + empty map 메모리 할당: 검증기 구조체 1개 + 빈 슬라이스 + 빈 맵

Example / 예제:

// String validation / 문자열 검증
v := validation.New("john@example.com", "email")
v.Required().Email()

// Numeric validation / 숫자 검증
v := validation.New(25, "age")
v.Required().Min(18).Max(120)

// Nil value validation / Nil 값 검증
v := validation.New(nil, "optional_field")
v.Email()  // Will pass if nil (optional)

// Complex validation chain / 복잡한 검증 체인
v := validation.New(username, "username")
v.Required().MinLength(3).MaxLength(20).AlphaNumeric()
Example

ExampleNew demonstrates creating a new validator ExampleNew는 새 검증기 생성을 보여줍니다

package main

import (
	"fmt"

	"github.com/arkd0ng/go-utils/validation"
)

func main() {
	v := validation.New("john@example.com", "email")
	v.Required().Email()
	err := v.Validate()
	if err != nil {
		fmt.Println("Validation failed")
	} else {
		fmt.Println("Validation passed")
	}
}
Output:

Validation passed

func (*Validator) ASCII

func (v *Validator) ASCII() *Validator

ASCII validates that the value contains only ASCII characters (0-127). Checks that all characters are in the standard ASCII range.

ASCII는 값이 ASCII 문자(0-127)만 포함하는지 검증합니다. 모든 문자가 표준 ASCII 범위에 있는지 확인합니다.

Parameters / 매개변수:

  • None (operates on validator's value) 없음 (validator의 값에 대해 작동)

Returns / 반환:

  • *Validator: Returns self for method chaining 메서드 체이닝을 위해 자신을 반환

Behavior / 동작:

  • Checks ASCII range: 0-127 ASCII 범위 확인: 0-127
  • Includes control characters (0-31, 127) 제어 문자 포함 (0-31, 127)
  • Includes printable characters (32-126) 인쇄 가능한 문자 포함 (32-126)
  • Fails on any non-ASCII character ASCII가 아닌 문자가 있으면 실패

Use Cases / 사용 사례:

  • Legacy system compatibility / 레거시 시스템 호환성
  • File format restrictions / 파일 형식 제한
  • Protocol compliance / 프로토콜 준수
  • Data encoding validation / 데이터 인코딩 검증

Thread Safety / 스레드 안전성:

  • Thread-safe: No shared state / 스레드 안전: 공유 상태 없음

Performance / 성능:

  • Time complexity: O(n), n = string length 시간 복잡도: O(n), n = 문자열 길이
  • Single pass character check 단일 패스 문자 확인

ASCII characters include all printable and control characters in the range 0-127. ASCII 문자는 0-127 범위의 모든 인쇄 가능 및 제어 문자를 포함합니다.

Example / 예시:

// Valid ASCII / 유효한 ASCII
text := "Hello World 123"
v := validation.New(text, "ascii_text")
v.ASCII()  // Passes

// With newline / 줄바꿈 포함
v = validation.New("Line1\nLine2", "text")
v.ASCII()  // Passes (control char allowed)

// Invalid - contains Unicode / 무효 - 유니코드 포함
v = validation.New("Hello 世界", "text")
v.ASCII()  // Fails (非ASCII)

Validation rules / 검증 규칙:

  • Must be a string / 문자열이어야 함
  • All characters must be in ASCII range (0-127) / 모든 문자가 ASCII 범위(0-127)
Example

ExampleValidator_ASCII demonstrates ASCII character validation. ExampleValidator_ASCII는 ASCII 문자 검증을 보여줍니다.

package main

import (
	"fmt"

	"github.com/arkd0ng/go-utils/validation"
)

func main() {
	v := validation.New("Hello World 123", "text")
	v.ASCII()

	err := v.Validate()
	if err != nil {
		fmt.Println("Invalid ASCII")
	} else {
		fmt.Println("Valid ASCII")
	}
}
Output:

Valid ASCII

func (*Validator) After

func (v *Validator) After(t time.Time) *Validator

After validates that the time value is strictly after the given time. Only works with time.Time values. Uses time.After() for comparison.

After는 시간 값이 주어진 시간보다 엄격하게 이후인지 검증합니다. time.Time 값에서만 작동합니다. 비교에 time.After()를 사용합니다.

Parameters / 매개변수:

  • t: The threshold time (exclusive) 임계 시간 (미포함)

Returns / 반환:

  • *Validator: Returns self for method chaining 메서드 체이닝을 위해 자신을 반환

Behavior / 동작:

  • Uses time.After() for comparison 비교에 time.After() 사용
  • Exclusive comparison (exact time fails) 미포함 비교 (정확히 같으면 실패)
  • Timezone-aware comparison 시간대 인식 비교
  • Fails if value is not time.Time 값이 time.Time이 아니면 실패

Use Cases / 사용 사례:

  • Future date validation / 미래 날짜 검증
  • Event start time validation / 이벤트 시작 시간 검증
  • Minimum date requirements / 최소 날짜 요구사항
  • After-hours validation / 업무 시간 이후 검증
  • Chronological order validation / 시간순 검증

Thread Safety / 스레드 안전성:

  • Thread-safe: No shared state / 스레드 안전: 공유 상태 없음

Performance / 성능:

  • Time complexity: O(1) 시간 복잡도: O(1)
  • Direct time comparison 직접 시간 비교

Timezone Considerations / 시간대 고려사항:

  • Compares absolute time, not wall clock time 벽시계 시간이 아닌 절대 시간 비교
  • Timezone differences handled correctly 시간대 차이 올바르게 처리
  • Use UTC for consistent comparisons 일관된 비교를 위해 UTC 사용

Example / 예제:

// Future date validation / 미래 날짜 검증
now := time.Now()
v := validation.New(eventDate, "event_date")
v.After(now)  // Event must be in the future

// Start after reference / 참조 이후 시작
referenceTime := time.Date(2024, 1, 1, 0, 0, 0, 0, time.UTC)
v := validation.New(startTime, "start_time")
v.After(referenceTime)

// Event sequence / 이벤트 순서
v := validation.New(endTime, "end_time")
v.After(startTime)  // End must be after start

// Exact time fails / 정확한 시간 실패
now := time.Now()
v := validation.New(now, "time")
v.After(now)  // Fails (not strictly after)
Example

ExampleValidator_After demonstrates the After validator ExampleValidator_After는 After 검증기를 보여줍니다

package main

import (
	"fmt"
	"time"

	"github.com/arkd0ng/go-utils/validation"
)

func main() {
	now := time.Now()
	tomorrow := now.Add(24 * time.Hour)
	v := validation.New(tomorrow, "date")
	v.After(now)
	err := v.Validate()
	if err != nil {
		fmt.Println("Date not after now")
	} else {
		fmt.Println("Valid date")
	}
}
Output:

Valid date

func (*Validator) AfterOrEqual

func (v *Validator) AfterOrEqual(t time.Time) *Validator

AfterOrEqual validates that the time value is after or equal to the given time. Only works with time.Time values. Inclusive comparison allowing exact time match.

AfterOrEqual은 시간 값이 주어진 시간보다 이후이거나 같은지 검증합니다. time.Time 값에서만 작동합니다. 정확한 시간 일치를 허용하는 포함 비교입니다.

Parameters / 매개변수:

  • t: The threshold time (inclusive) 임계 시간 (포함)

Returns / 반환:

  • *Validator: Returns self for method chaining 메서드 체이닝을 위해 자신을 반환

Behavior / 동작:

  • Accepts if time is after OR equal to threshold 시간이 임계값 이후이거나 같으면 허용
  • Inclusive comparison (exact time passes) 포함 비교 (정확히 같으면 통과)
  • Uses !timeVal.Before(t) for implementation 구현에 !timeVal.Before(t) 사용
  • Timezone-aware comparison 시간대 인식 비교
  • Fails if value is not time.Time 값이 time.Time이 아니면 실패

Use Cases / 사용 사례:

  • Minimum date validation / 최소 날짜 검증
  • Start date validation / 시작 날짜 검증
  • Future or current date validation / 미래 또는 현재 날짜 검증
  • Availability start time / 가용성 시작 시간

Thread Safety / 스레드 안전성:

  • Thread-safe: No shared state / 스레드 안전: 공유 상태 없음

Performance / 성능:

  • Time complexity: O(1) 시간 복잡도: O(1)
  • Direct time comparison 직접 시간 비교

Example / 예제:

// Minimum start date / 최소 시작 날짜
minDate := time.Date(2024, 1, 1, 0, 0, 0, 0, time.UTC)
v := validation.New(startDate, "start_date")
v.AfterOrEqual(minDate)  // Can start on or after 2024-01-01

// Current or future date / 현재 또는 미래 날짜
now := time.Now()
v := validation.New(eventDate, "event_date")
v.AfterOrEqual(now)  // Can be today or later

// Exact time passes / 정확한 시간 통과
startTime := time.Now()
v := validation.New(startTime, "time")
v.AfterOrEqual(startTime)  // Passes (equal allowed)

func (*Validator) Alpha

func (v *Validator) Alpha() *Validator

Alpha validates that the string contains only letters (alphabetic characters). Supports Unicode letters from all languages including CJK, Cyrillic, Arabic, etc.

Alpha는 문자열이 문자(알파벳)만 포함하는지 검증합니다. 한중일, 키릴 문자, 아랍 문자 등 모든 언어의 유니코드 문자를 지원합니다.

Character Rules / 문자 규칙:

  • Only Unicode letters allowed (L category) 유니코드 문자만 허용 (L 카테고리)
  • No digits, spaces, punctuation, or special characters 숫자, 공백, 구두점, 특수 문자 불허
  • Supports all language scripts 모든 언어 스크립트 지원

Valid Examples / 유효한 예:

  • "Hello"
  • "안녕하세요"
  • "Привет" (Russian / 러시아어)
  • "مرحبا" (Arabic / 아랍어)

Invalid Examples / 유효하지 않은 예:

  • "Hello123" (contains digits)
  • "Hello World" (contains space)
  • "Hello!" (contains punctuation)
  • "" (empty string)

Returns / 반환:

  • *Validator: Returns self for method chaining 메서드 체이닝을 위해 자신을 반환

Behavior / 동작:

  • Iterates through each rune 각 rune을 반복
  • Uses unicode.IsLetter() for validation unicode.IsLetter()를 사용하여 검증
  • Empty string passes validation (use Required() to prevent) 빈 문자열은 검증 통과 (방지하려면 Required() 사용)
  • Skips validation if value is not a string 값이 문자열이 아니면 검증 건너뜀

Use Cases / 사용 사례:

  • Name fields (first name, last name) 이름 필드 (성, 이름)
  • Language-only input / 언어 전용 입력
  • Text-only fields / 텍스트 전용 필드
  • International names / 국제 이름

Thread Safety / 스레드 안전성:

  • Thread-safe: No shared state / 스레드 안전: 공유 상태 없음

Performance / 성능:

  • Time complexity: O(n) where n is string length 시간 복잡도: O(n) (n은 문자열 길이)
  • Checks each rune individually 각 rune을 개별적으로 검사

Example / 예제:

v := validation.New("John", "firstname")
v.Alpha()  // Passes / 성공

v := validation.New("John123", "firstname")
v.Alpha()  // Fails / 실패

v := validation.New("김철수", "name")
v.Alpha()  // Passes / 성공

// Name validation / 이름 검증
v := validation.New(name, "name")
v.Required().Alpha().MinLength(2).MaxLength(50)

func (*Validator) AlphaSpace

func (v *Validator) AlphaSpace() *Validator

AlphaSpace validates that the value contains only alphabetic characters and spaces. Uses unicode.IsLetter for comprehensive letter detection including Unicode characters.

AlphaSpace는 값이 알파벳 문자와 공백만 포함하는지 검증합니다. 유니코드 문자를 포함한 포괄적인 문자 감지를 위해 unicode.IsLetter를 사용합니다.

Parameters / 매개변수:

  • None (operates on validator's value) 없음 (validator의 값에 대해 작동)

Returns / 반환:

  • *Validator: Returns self for method chaining 메서드 체이닝을 위해 자신을 반환

Behavior / 동작:

  • Allows Unicode letters (all languages) 유니코드 문자 허용 (모든 언어)
  • Allows space character 공백 문자 허용
  • Rejects numbers 숫자 거부
  • Rejects punctuation and symbols 구두점 및 기호 거부

Use Cases / 사용 사례:

  • Full name validation / 전체 이름 검증
  • Person name fields / 개인 이름 필드
  • Text-only input / 텍스트 전용 입력
  • Multi-language name support / 다국어 이름 지원

Thread Safety / 스레드 안전성:

  • Thread-safe: No shared state / 스레드 안전: 공유 상태 없음

Performance / 성능:

  • Time complexity: O(n), n = string length 시간 복잡도: O(n), n = 문자열 길이
  • Single pass Unicode check 단일 패스 유니코드 확인

This validator checks for letters (a-z, A-Z) and space characters only. No numbers or special characters are allowed. 이 검증기는 문자(a-z, A-Z)와 공백 문자만 확인합니다. 숫자나 특수 문자는 허용되지 않습니다.

Example / 예시:

// Valid name / 유효한 이름
name := "John Doe"
v := validation.New(name, "full_name")
v.AlphaSpace()  // Passes

// Single word / 단일 단어
v = validation.New("Alice", "first_name")
v.AlphaSpace()  // Passes

// Unicode letters / 유니코드 문자
v = validation.New("김철수", "name")
v.AlphaSpace()  // Passes

// Invalid - contains number / 무효 - 숫자 포함
v = validation.New("John123", "name")
v.AlphaSpace()  // Fails

// Invalid - contains punctuation / 무효 - 구두점 포함
v = validation.New("O'Brien", "name")
v.AlphaSpace()  // Fails

Validation rules / 검증 규칙:

  • Must be a string / 문자열이어야 함
  • Only letters and spaces allowed / 문자와 공백만 허용
  • No numbers or special characters / 숫자나 특수 문자 없음
Example

ExampleValidator_AlphaSpace demonstrates alpha+space validation. ExampleValidator_AlphaSpace는 문자와 공백만 있는지 검증을 보여줍니다.

package main

import (
	"fmt"

	"github.com/arkd0ng/go-utils/validation"
)

func main() {
	v := validation.New("John Doe", "name")
	v.AlphaSpace()

	err := v.Validate()
	if err != nil {
		fmt.Println("Invalid name")
	} else {
		fmt.Println("Valid name")
	}
}
Output:

Valid name

func (*Validator) Alphanumeric

func (v *Validator) Alphanumeric() *Validator

Alphanumeric validates that the string contains only letters and numbers. Supports Unicode letters and digits from all languages.

Alphanumeric은 문자열이 문자와 숫자만 포함하는지 검증합니다. 모든 언어의 유니코드 문자와 숫자를 지원합니다.

Character Rules / 문자 규칙:

  • Unicode letters (L category) allowed 유니코드 문자 허용 (L 카테고리)
  • Unicode digits (Nd category) allowed 유니코드 숫자 허용 (Nd 카테고리)
  • No spaces, punctuation, or special characters 공백, 구두점, 특수 문자 불허
  • Supports international characters and digits 국제 문자와 숫자 지원

Valid Examples / 유효한 예:

  • "abc123"
  • "User123"
  • "김철수123"
  • "١٢٣abc" (Arabic digits / 아랍 숫자)

Invalid Examples / 유효하지 않은 예:

  • "abc 123" (contains space)
  • "user_123" (contains underscore)
  • "user-123" (contains hyphen)
  • "user@123" (contains special char)

Returns / 반환:

  • *Validator: Returns self for method chaining 메서드 체이닝을 위해 자신을 반환

Behavior / 동작:

  • Iterates through each rune 각 rune을 반복
  • Uses unicode.IsLetter() and unicode.IsDigit() unicode.IsLetter() 및 unicode.IsDigit() 사용
  • Empty string passes validation (use Required() to prevent) 빈 문자열은 검증 통과 (방지하려면 Required() 사용)
  • Skips validation if value is not a string 값이 문자열이 아니면 검증 건너뜀

Use Cases / 사용 사례:

  • Username validation / 사용자명 검증
  • Product codes / 제품 코드
  • Reference numbers / 참조 번호
  • Identifiers without special characters / 특수 문자 없는 식별자

Thread Safety / 스레드 안전성:

  • Thread-safe: No shared state / 스레드 안전: 공유 상태 없음

Performance / 성능:

  • Time complexity: O(n) where n is string length 시간 복잡도: O(n) (n은 문자열 길이)
  • Checks each rune individually 각 rune을 개별적으로 검사

Example / 예제:

v := validation.New("User123", "username")
v.Alphanumeric()  // Passes / 성공

v := validation.New("User_123", "username")
v.Alphanumeric()  // Fails / 실패

v := validation.New("사용자123", "username")
v.Alphanumeric()  // Passes / 성공

// Username validation / 사용자명 검증
v := validation.New(username, "username")
v.Required().Alphanumeric().MinLength(3).MaxLength(20)

func (*Validator) ArrayLength

func (v *Validator) ArrayLength(length int) *Validator

ArrayLength validates that the array or slice has exactly the specified length. Works with both arrays and slices. Fails if value is not an array/slice type.

ArrayLength는 배열 또는 슬라이스가 정확히 지정된 길이를 가지는지 검증합니다. 배열과 슬라이스 모두에서 작동합니다. 값이 배열/슬라이스 타입이 아니면 실패합니다.

Parameters / 매개변수:

  • length: Exact required length 필요한 정확한 길이

Returns / 반환:

  • *Validator: Returns self for method chaining 메서드 체이닝을 위해 자신을 반환

Behavior / 동작:

  • Uses reflection to get length 반사를 사용하여 길이 확인
  • Works with both arrays and slices 배열과 슬라이스 모두에서 작동
  • Fails if not array/slice type 배열/슬라이스 타입이 아니면 실패
  • Exact match required (not >=, not <=) 정확히 일치 필요 (이상/이하 아님)

Use Cases / 사용 사례:

  • Fixed-size collection validation / 고정 크기 컬렉션 검증
  • Coordinate tuples (x, y, z) / 좌표 튜플 (x, y, z)
  • RGB color arrays [R, G, B] / RGB 색상 배열
  • Fixed parameter counts / 고정 매개변수 수
  • Matrix dimensions / 행렬 차원

Thread Safety / 스레드 안전성:

  • Thread-safe: No shared state / 스레드 안전: 공유 상태 없음

Performance / 성능:

  • Time complexity: O(1) 시간 복잡도: O(1)
  • Reflection overhead for type checking 타입 검사를 위한 반사 오버헤드

Example / 예제:

// Exact length / 정확한 길이
v := validation.New([]int{1, 2, 3}, "numbers")
v.ArrayLength(3)  // Passes / 성공

v := validation.New([]int{1, 2}, "numbers")
v.ArrayLength(3)  // Fails (too short) / 실패 (너무 짧음)

// RGB color validation / RGB 색상 검증
v := validation.New([3]int{255, 128, 64}, "rgb")
v.ArrayLength(3)  // Passes / 성공

// Coordinate validation / 좌표 검증
v := validation.New(coords, "coordinates")
v.ArrayNotEmpty().ArrayLength(3) // Must be [x, y, z]

// Invalid type / 유효하지 않은 타입
v := validation.New("string", "value")
v.ArrayLength(3)  // Fails (not array/slice) / 실패 (배열/슬라이스 아님)
Example

ExampleValidator_ArrayLength demonstrates the ArrayLength validator ExampleValidator_ArrayLength는 ArrayLength 검증기를 보여줍니다

package main

import (
	"fmt"

	"github.com/arkd0ng/go-utils/validation"
)

func main() {
	v := validation.New([]int{1, 2, 3}, "numbers")
	v.ArrayLength(3)
	err := v.Validate()
	if err != nil {
		fmt.Println("Invalid array length")
	} else {
		fmt.Println("Valid array length")
	}
}
Output:

Valid array length

func (*Validator) ArrayMaxLength

func (v *Validator) ArrayMaxLength(max int) *Validator

ArrayMaxLength validates that the array or slice has at most the maximum length. Works with both arrays and slices. Fails if value is not an array/slice type.

ArrayMaxLength는 배열 또는 슬라이스가 최대 길이를 넘지 않는지 검증합니다. 배열과 슬라이스 모두에서 작동합니다. 값이 배열/슬라이스 타입이 아니면 실패합니다.

Parameters / 매개변수:

  • max: Maximum allowed length (inclusive) 허용되는 최대 길이 (포함)

Returns / 반환:

  • *Validator: Returns self for method chaining 메서드 체이닝을 위해 자신을 반환

Behavior / 동작:

  • Uses reflection to get length 반사를 사용하여 길이 확인
  • Works with both arrays and slices 배열과 슬라이스 모두에서 작동
  • Fails if not array/slice type 배열/슬라이스 타입이 아니면 실패
  • Inclusive comparison (length == max is valid) 포함 비교 (길이 == 최대값 유효)

Use Cases / 사용 사례:

  • Maximum item limits / 최대 항목 제한
  • API response size limits / API 응답 크기 제한
  • Form validation (select at most N items) 폼 검증 (최대 N개 항목 선택)
  • Batch size limits / 배치 크기 제한
  • Memory constraints / 메모리 제약

Thread Safety / 스레드 안전성:

  • Thread-safe: No shared state / 스레드 안전: 공유 상태 없음

Performance / 성능:

  • Time complexity: O(1) 시간 복잡도: O(1)
  • Reflection overhead for type checking 타입 검사를 위한 반사 오버헤드

Example / 예제:

// Maximum items / 최대 항목
v := validation.New([]int{1, 2, 3}, "numbers")
v.ArrayMaxLength(5)  // Passes / 성공

v := validation.New([]int{1, 2, 3, 4, 5, 6}, "numbers")
v.ArrayMaxLength(5)  // Fails / 실패

v := validation.New([]string{"a", "b", "c"}, "items")
v.ArrayMaxLength(3)  // Passes (boundary) / 성공 (경계값)

// Limit selections / 선택 제한
v := validation.New(selectedOptions, "options")
v.ArrayNotEmpty().ArrayMaxLength(3)

// Batch size limit / 배치 크기 제한
v := validation.New(batch, "batch")
v.ArrayMinLength(1).ArrayMaxLength(100)
Example

ExampleValidator_ArrayMaxLength demonstrates the ArrayMaxLength validator ExampleValidator_ArrayMaxLength는 ArrayMaxLength 검증기를 보여줍니다

package main

import (
	"fmt"

	"github.com/arkd0ng/go-utils/validation"
)

func main() {
	v := validation.New([]string{"a", "b"}, "items")
	v.ArrayMaxLength(5)
	err := v.Validate()
	if err != nil {
		fmt.Println("Array too long")
	} else {
		fmt.Println("Valid array length")
	}
}
Output:

Valid array length

func (*Validator) ArrayMinLength

func (v *Validator) ArrayMinLength(min int) *Validator

ArrayMinLength validates that the array or slice has at least the minimum length. Works with both arrays and slices. Fails if value is not an array/slice type.

ArrayMinLength는 배열 또는 슬라이스가 최소 길이를 가지는지 검증합니다. 배열과 슬라이스 모두에서 작동합니다. 값이 배열/슬라이스 타입이 아니면 실패합니다.

Parameters / 매개변수:

  • min: Minimum required length (inclusive) 필요한 최소 길이 (포함)

Returns / 반환:

  • *Validator: Returns self for method chaining 메서드 체이닝을 위해 자신을 반환

Behavior / 동작:

  • Uses reflection to get length 반사를 사용하여 길이 확인
  • Works with both arrays and slices 배열과 슬라이스 모두에서 작동
  • Fails if not array/slice type 배열/슬라이스 타입이 아니면 실패
  • Inclusive comparison (length == min is valid) 포함 비교 (길이 == 최소값 유효)

Use Cases / 사용 사례:

  • Minimum item requirements / 최소 항목 요구사항
  • Batch processing (minimum batch size) 배치 처리 (최소 배치 크기)
  • Form validation (select at least N items) 폼 검증 (최소 N개 항목 선택)
  • Required options selection / 필수 옵션 선택

Thread Safety / 스레드 안전성:

  • Thread-safe: No shared state / 스레드 안전: 공유 상태 없음

Performance / 성능:

  • Time complexity: O(1) 시간 복잡도: O(1)
  • Reflection overhead for type checking 타입 검사를 위한 반사 오버헤드

Example / 예제:

// Minimum items / 최소 항목
v := validation.New([]string{"a", "b", "c"}, "items")
v.ArrayMinLength(2)  // Passes / 성공

v := validation.New([]string{"a"}, "items")
v.ArrayMinLength(2)  // Fails / 실패

v := validation.New([]int{1, 2}, "numbers")
v.ArrayMinLength(2)  // Passes (boundary) / 성공 (경계값)

// Multiple selections / 다중 선택
v := validation.New(selectedItems, "selections")
v.ArrayNotEmpty().ArrayMinLength(1).ArrayMaxLength(10)

// Batch validation / 배치 검증
v := validation.New(batch, "batch")
v.ArrayMinLength(10) // Minimum 10 items per batch
Example

ExampleValidator_ArrayMinLength demonstrates the ArrayMinLength validator ExampleValidator_ArrayMinLength는 ArrayMinLength 검증기를 보여줍니다

package main

import (
	"fmt"

	"github.com/arkd0ng/go-utils/validation"
)

func main() {
	v := validation.New([]string{"a", "b", "c"}, "items")
	v.ArrayMinLength(2)
	err := v.Validate()
	if err != nil {
		fmt.Println("Array too short")
	} else {
		fmt.Println("Valid array length")
	}
}
Output:

Valid array length

func (*Validator) ArrayNotEmpty

func (v *Validator) ArrayNotEmpty() *Validator

ArrayNotEmpty validates that the array or slice is not empty (has at least one element). Works with both arrays and slices. Fails if value is not an array/slice type.

ArrayNotEmpty는 배열 또는 슬라이스가 비어있지 않은지 (최소 하나의 요소 포함) 검증합니다. 배열과 슬라이스 모두에서 작동합니다. 값이 배열/슬라이스 타입이 아니면 실패합니다.

Returns / 반환:

  • *Validator: Returns self for method chaining 메서드 체이닝을 위해 자신을 반환

Behavior / 동작:

  • Uses reflection to check length 반사를 사용하여 길이 확인
  • Works with both arrays and slices 배열과 슬라이스 모두에서 작동
  • Fails if not array/slice type 배열/슬라이스 타입이 아니면 실패
  • Fails if length is zero 길이가 0이면 실패

Use Cases / 사용 사례:

  • Required collection validation / 필수 컬렉션 검증
  • Ensure selection made / 선택 확인
  • Non-empty result validation / 비어있지 않은 결과 검증
  • Required items in cart / 장바구니의 필수 항목
  • Attachment requirement / 첨부 파일 요구사항

Thread Safety / 스레드 안전성:

  • Thread-safe: No shared state / 스레드 안전: 공유 상태 없음

Performance / 성능:

  • Time complexity: O(1) 시간 복잡도: O(1)
  • Reflection overhead for type checking 타입 검사를 위한 반사 오버헤드

Note / 참고:

  • Equivalent to ArrayMinLength(1) ArrayMinLength(1)과 동등
  • More semantic and readable 더 의미론적이고 읽기 쉬움

Example / 예제:

// Must have items / 항목 필수
v := validation.New([]string{"item"}, "items")
v.ArrayNotEmpty()  // Passes / 성공

v := validation.New([]string{}, "items")
v.ArrayNotEmpty()  // Fails / 실패

v := validation.New([]int{0}, "numbers")
v.ArrayNotEmpty()  // Passes (has one element) / 성공 (요소 하나 있음)

// Shopping cart / 장바구니
v := validation.New(cartItems, "cart")
v.ArrayNotEmpty() // Cart must have items

// File attachments / 파일 첨부
v := validation.New(attachments, "attachments")
v.ArrayNotEmpty().ArrayMaxLength(5)

func (*Validator) ArrayUnique

func (v *Validator) ArrayUnique() *Validator

ArrayUnique validates that all elements in the array or slice are unique (no duplicates). Works with both arrays and slices. Fails if value is not an array/slice type.

ArrayUnique는 배열 또는 슬라이스의 모든 요소가 고유한지 (중복 없음) 검증합니다. 배열과 슬라이스 모두에서 작동합니다. 값이 배열/슬라이스 타입이 아니면 실패합니다.

Returns / 반환:

  • *Validator: Returns self for method chaining 메서드 체이닝을 위해 자신을 반환

Behavior / 동작:

  • Uses map to track seen elements 본 요소를 추적하기 위해 맵 사용
  • Works with both arrays and slices 배열과 슬라이스 모두에서 작동
  • Fails if not array/slice type 배열/슬라이스 타입이 아니면 실패
  • Fails on first duplicate found 첫 번째 중복을 찾으면 실패
  • Empty arrays/slices pass validation 빈 배열/슬라이스는 검증 통과

Use Cases / 사용 사례:

  • Unique ID validation / 고유 ID 검증
  • Unique tag/category lists / 고유 태그/카테고리 목록
  • Prevent duplicate selections / 중복 선택 방지
  • Unique email lists / 고유 이메일 목록
  • Set-like behavior validation / 집합 유사 동작 검증

Thread Safety / 스레드 안전성:

  • Thread-safe: No shared state / 스레드 안전: 공유 상태 없음

Performance / 성능:

  • Time complexity: O(n) where n is array length 시간 복잡도: O(n) (n은 배열 길이)
  • Space complexity: O(n) for tracking seen elements 공간 복잡도: O(n) (본 요소 추적)
  • Early termination on duplicate found 중복 발견 시 조기 종료

Limitations / 제한사항:

  • Elements must be map-key compatible 요소는 맵 키 호환 가능해야 함
  • Complex types (slices, maps) may not work as expected 복잡한 타입 (슬라이스, 맵)은 예상대로 작동하지 않을 수 있음

Example / 예제:

// Unique numbers / 고유 숫자
v := validation.New([]int{1, 2, 3}, "numbers")
v.ArrayUnique()  // Passes / 성공

v := validation.New([]int{1, 2, 2, 3}, "numbers")
v.ArrayUnique()  // Fails (duplicate 2) / 실패 (중복 2)

// Unique strings / 고유 문자열
v := validation.New([]string{"a", "b", "c"}, "tags")
v.ArrayUnique()  // Passes / 성공

// Empty array / 빈 배열
v := validation.New([]int{}, "numbers")
v.ArrayUnique()  // Passes (no duplicates) / 성공 (중복 없음)

// Unique IDs / 고유 ID
v := validation.New(userIDs, "user_ids")
v.ArrayNotEmpty().ArrayUnique()

// Unique tags / 고유 태그
v := validation.New(tags, "tags")
v.ArrayUnique().ArrayMaxLength(10)
Example

ExampleValidator_ArrayUnique demonstrates the ArrayUnique validator ExampleValidator_ArrayUnique는 ArrayUnique 검증기를 보여줍니다

package main

import (
	"fmt"

	"github.com/arkd0ng/go-utils/validation"
)

func main() {
	v := validation.New([]int{1, 2, 3, 4, 5}, "numbers")
	v.ArrayUnique()
	err := v.Validate()
	if err != nil {
		fmt.Println("Duplicate values found")
	} else {
		fmt.Println("All values unique")
	}
}
Output:

All values unique

func (*Validator) BCrypt

func (v *Validator) BCrypt() *Validator

BCrypt validates that the value is a valid BCrypt hash. Validates the BCrypt hash format with cost factor and encoded salt/hash.

BCrypt는 값이 유효한 BCrypt 해시인지 검증합니다. 비용 계수 및 인코딩된 솔트/해시를 포함한 BCrypt 해시 형식을 검증합니다.

Parameters / 매개변수:

  • None (operates on validator's value) 없음 (validator의 값에 대해 작동)

Returns / 반환:

  • *Validator: Returns self for method chaining 메서드 체이닝을 위해 자신을 반환

Behavior / 동작:

  • Validates BCrypt identifier ($2a$, $2b$, $2x$, $2y$) BCrypt 식별자 검증 ($2a$, $2b$, $2x$, $2y$)
  • Validates cost factor (00-31) 비용 계수 검증 (00-31)
  • Validates 60-character length 60자 길이 검증
  • Validates base64 salt/hash encoding base64 솔트/해시 인코딩 검증

Use Cases / 사용 사례:

  • Password hash storage / 비밀번호 해시 저장
  • Database hash validation / 데이터베이스 해시 검증
  • Authentication systems / 인증 시스템
  • Security compliance / 보안 규정 준수

Thread Safety / 스레드 안전성:

  • Thread-safe: No shared state / 스레드 안전: 공유 상태 없음

Performance / 성능:

  • Time complexity: O(1), fixed length check 시간 복잡도: O(1), 고정 길이 확인
  • Regex pattern matching 정규식 패턴 매칭

BCrypt hashes start with $2a$, $2b$, $2x$, or $2y$ followed by cost and salt. BCrypt 해시는 $2a$, $2b$, $2x$, 또는 $2y$로 시작하며 비용과 솔트가 따릅니다.

Example / 예시:

// Valid BCrypt hash / 유효한 BCrypt 해시
hash := "$2a$10$N9qo8uLOickgx2ZMRZoMyeIjZAgcfl7p92ldGxad68LJZdL17lhWy"
v := validation.New(hash, "password_hash")
v.BCrypt()  // Passes

// Higher cost factor / 높은 비용 계수
hash = "$2b$12$KCgZvfKlYH2PvzNLn5C4veWmJ3dP5HlN4KJlBp4LwBd0XYZ1qR4Qi"
v = validation.New(hash, "hash")
v.BCrypt()  // Passes

// Invalid - wrong length / 무효 - 잘못된 길이
v = validation.New("$2a$10$short", "hash")
v.BCrypt()  // Fails

// Invalid - wrong format / 무효 - 잘못된 형식
v = validation.New("not-a-bcrypt-hash", "hash")
v.BCrypt()  // Fails

Validation rules / 검증 규칙:

  • Must be a string / 문자열이어야 함
  • Must start with $2a$, $2b$, $2x$, or $2y$ / $2a$, $2b$, $2x$, 또는 $2y$로 시작
  • Must be 60 characters long / 60자여야 함
  • Must match BCrypt format / BCrypt 형식과 일치해야 함
Example

ExampleValidator_BCrypt demonstrates BCrypt hash validation ExampleValidator_BCrypt는 BCrypt 해시 검증을 보여줍니다

package main

import (
	"fmt"

	"github.com/arkd0ng/go-utils/validation"
)

func main() {
	hash := "$2a$10$N9qo8uLOickgx2ZMRZoMyeIjZAgcfl7p92ldGxad68LJZdL17lhWy"
	v := validation.New(hash, "password_hash")
	v.BCrypt()

	if len(v.GetErrors()) > 0 {
		fmt.Println("Invalid BCrypt hash")
	} else {
		fmt.Println("Valid BCrypt hash")
	}
}
Output:

Valid BCrypt hash

func (*Validator) Base64

func (v *Validator) Base64() *Validator

Base64 validates that the string is valid Base64 encoding. Uses standard Base64 encoding (RFC 4648).

Base64는 문자열이 유효한 Base64 인코딩인지 검증합니다. 표준 Base64 인코딩 (RFC 4648)을 사용합니다.

Format Rules / 형식 규칙:

  • Characters: A-Z, a-z, 0-9, +, / 문자: A-Z, a-z, 0-9, +, /
  • Padding: = character for alignment 패딩: 정렬을 위한 = 문자
  • Length must be multiple of 4 길이는 4의 배수여야 함
  • Whitespace not allowed 공백 허용 안 됨

Valid Examples / 유효한 예:

  • "SGVsbG8=" (encodes "Hello")
  • "SGVsbG8gV29ybGQ=" (encodes "Hello World")
  • "YWJjMTIz" (encodes "abc123")
  • "MTIzNDU2Nzg5MA==" (with padding)

Invalid Examples / 유효하지 않은 예:

  • "Hello!" (not Base64)
  • "SGVsbG8" (missing padding)
  • "SGVs bG8=" (contains space)
  • "SGVsbG8==" (incorrect padding)

Returns / 반환:

  • *Validator: Returns self for method chaining 메서드 체이닝을 위해 자신을 반환

Behavior / 동작:

  • Uses base64.StdEncoding.DecodeString() base64.StdEncoding.DecodeString() 사용
  • Attempts to decode the string 문자열 디코딩 시도
  • Fails if decoding returns error 디코딩이 오류 반환하면 실패
  • Does not validate decoded content 디코딩된 내용은 검증하지 않음
  • Skips validation if value is not a string 값이 문자열이 아니면 검증 건너뜀

Use Cases / 사용 사례:

  • File upload (base64 encoded files) 파일 업로드 (base64 인코딩 파일)
  • Image data validation / 이미지 데이터 검증
  • Encoded credentials / 인코딩된 자격 증명
  • Binary data transmission / 바이너리 데이터 전송

Thread Safety / 스레드 안전성:

  • Thread-safe: No shared state / 스레드 안전: 공유 상태 없음

Performance / 성능:

  • Time complexity: O(n) where n is string length 시간 복잡도: O(n) (n은 문자열 길이)
  • Full decode operation overhead 전체 디코드 작업 오버헤드
  • Memory allocation for decoded bytes 디코딩된 바이트를 위한 메모리 할당

Encoding Standards / 인코딩 표준:

  • Standard Base64 (RFC 4648): +, / 표준 Base64 (RFC 4648): +, /
  • URL-safe Base64 not supported: -, _ URL 안전 Base64 미지원: -, _
  • Base64URL requires different validator Base64URL은 다른 검증기 필요

Example / 예제:

v := validation.New("SGVsbG8gV29ybGQ=", "encoded")
v.Base64()  // Passes / 성공

v := validation.New("Not Base64!", "encoded")
v.Base64()  // Fails / 실패

v := validation.New("SGVsbG8", "encoded")
v.Base64()  // Fails (missing padding) / 실패 (패딩 누락)

// Image upload validation / 이미지 업로드 검증
v := validation.New(imageData, "image")
v.Required().Base64().MaxLength(1048576) // 1MB limit

// Decode after validation / 검증 후 디코딩
if v.IsValid() {
    decoded, _ := base64.StdEncoding.DecodeString(imageData)
    // Process decoded data / 디코딩된 데이터 처리
}

func (*Validator) Before

func (v *Validator) Before(t time.Time) *Validator

Before validates that the time value is strictly before the given time. Only works with time.Time values. Uses time.Before() for comparison.

Before는 시간 값이 주어진 시간보다 엄격하게 이전인지 검증합니다. time.Time 값에서만 작동합니다. 비교에 time.Before()를 사용합니다.

Parameters / 매개변수:

  • t: The threshold time (exclusive) 임계 시간 (미포함)

Returns / 반환:

  • *Validator: Returns self for method chaining 메서드 체이닝을 위해 자신을 반환

Behavior / 동작:

  • Uses time.Before() for comparison 비교에 time.Before() 사용
  • Exclusive comparison (exact time fails) 미포함 비교 (정확히 같으면 실패)
  • Timezone-aware comparison 시간대 인식 비교
  • Fails if value is not time.Time 값이 time.Time이 아니면 실패

Use Cases / 사용 사례:

  • Event deadline validation / 이벤트 마감 검증
  • Historical date validation / 과거 날짜 검증
  • Date range validation / 날짜 범위 검증
  • Expiration checks / 만료 확인
  • Start/end date validation / 시작/종료 날짜 검증

Thread Safety / 스레드 안전성:

  • Thread-safe: No shared state / 스레드 안전: 공유 상태 없음

Performance / 성능:

  • Time complexity: O(1) 시간 복잡도: O(1)
  • Direct time comparison 직접 시간 비교

Timezone Considerations / 시간대 고려사항:

  • Compares absolute time, not wall clock time 벽시계 시간이 아닌 절대 시간 비교
  • Timezone differences handled correctly 시간대 차이 올바르게 처리
  • Use UTC for consistent comparisons 일관된 비교를 위해 UTC 사용

Example / 예제:

// Deadline validation / 마감 검증
deadline := time.Date(2024, 12, 31, 23, 59, 59, 0, time.UTC)
v := validation.New(submittedTime, "submitted_at")
v.Before(deadline)  // Must be submitted before deadline

// Past date validation / 과거 날짜 검증
now := time.Now()
v := validation.New(birthDate, "birth_date")
v.Before(now)  // Birth date must be in the past

// Event scheduling / 이벤트 스케줄링
v := validation.New(startTime, "start_time")
v.Before(endTime)  // Start must be before end

// Exact time fails / 정확한 시간 실패
now := time.Now()
v := validation.New(now, "time")
v.Before(now)  // Fails (not strictly before)
Example

ExampleValidator_Before demonstrates the Before validator ExampleValidator_Before는 Before 검증기를 보여줍니다

package main

import (
	"fmt"
	"time"

	"github.com/arkd0ng/go-utils/validation"
)

func main() {
	now := time.Now()
	yesterday := now.Add(-24 * time.Hour)
	v := validation.New(yesterday, "date")
	v.Before(now)
	err := v.Validate()
	if err != nil {
		fmt.Println("Date not before now")
	} else {
		fmt.Println("Valid date")
	}
}
Output:

Valid date

func (*Validator) BeforeOrEqual

func (v *Validator) BeforeOrEqual(t time.Time) *Validator

BeforeOrEqual validates that the time value is before or equal to the given time. Only works with time.Time values. Inclusive comparison allowing exact time match.

BeforeOrEqual은 시간 값이 주어진 시간보다 이전이거나 같은지 검증합니다. time.Time 값에서만 작동합니다. 정확한 시간 일치를 허용하는 포함 비교입니다.

Parameters / 매개변수:

  • t: The threshold time (inclusive) 임계 시간 (포함)

Returns / 반환:

  • *Validator: Returns self for method chaining 메서드 체이닝을 위해 자신을 반환

Behavior / 동작:

  • Accepts if time is before OR equal to threshold 시간이 임계값 이전이거나 같으면 허용
  • Inclusive comparison (exact time passes) 포함 비교 (정확히 같으면 통과)
  • Uses !timeVal.After(t) for implementation 구현에 !timeVal.After(t) 사용
  • Timezone-aware comparison 시간대 인식 비교
  • Fails if value is not time.Time 값이 time.Time이 아니면 실패

Use Cases / 사용 사례:

  • Deadline validation (inclusive) / 마감 검증 (포함)
  • Maximum date validation / 최대 날짜 검증
  • End date validation / 종료 날짜 검증
  • Historical or current date validation / 과거 또는 현재 날짜 검증

Thread Safety / 스레드 안전성:

  • Thread-safe: No shared state / 스레드 안전: 공유 상태 없음

Performance / 성능:

  • Time complexity: O(1) 시간 복잡도: O(1)
  • Direct time comparison 직접 시간 비교

Example / 예제:

// Deadline validation (inclusive) / 마감 검증 (포함)
deadline := time.Date(2024, 12, 31, 23, 59, 59, 0, time.UTC)
v := validation.New(submittedTime, "submitted_at")
v.BeforeOrEqual(deadline)  // Can submit up to and including deadline

// Current or past date / 현재 또는 과거 날짜
now := time.Now()
v := validation.New(date, "date")
v.BeforeOrEqual(now)  // Can be today or earlier

// Exact time passes / 정확한 시간 통과
deadline := time.Now()
v := validation.New(deadline, "time")
v.BeforeOrEqual(deadline)  // Passes (equal allowed)

func (*Validator) Between

func (v *Validator) Between(min, max float64) *Validator

Between validates that the numeric value is within a specified range (inclusive). Works with all numeric types: int, int8-64, uint, uint8-64, float32, float64.

Between은 숫자 값이 지정된 범위 내에 있는지 검증합니다 (포함). 모든 숫자 타입에서 작동합니다: int, int8-64, uint, uint8-64, float32, float64.

Parameters / 매개변수:

  • min: Minimum value (inclusive) 최소값 (포함)
  • max: Maximum value (inclusive) 최대값 (포함)

Returns / 반환:

  • *Validator: Returns self for method chaining 메서드 체이닝을 위해 자신을 반환

Behavior / 동작:

  • Accepts value if min <= val <= max min <= val <= max이면 허용
  • Converts value to float64 for comparison 비교를 위해 값을 float64로 변환
  • Inclusive on both ends (boundaries are valid) 양 끝 포함 (경계값은 유효)
  • Skips validation if value is not numeric 값이 숫자가 아니면 검증 건너뜀

Use Cases / 사용 사례:

  • Age range validation / 나이 범위 검증
  • Price range filtering / 가격 범위 필터링
  • Percentage validation (0-100) / 백분율 검증 (0-100)
  • Rating systems (1-5, 1-10) / 평점 시스템 (1-5, 1-10)
  • Temperature ranges / 온도 범위

Thread Safety / 스레드 안전성:

  • Thread-safe: No shared state / 스레드 안전: 공유 상태 없음

Performance / 성능:

  • Time complexity: O(1) 시간 복잡도: O(1)
  • Two numeric comparisons 두 개의 숫자 비교

Example / 예제:

v := validation.New(25, "age")
v.Between(18, 65)  // Passes / 성공

v := validation.New(10, "age")
v.Between(18, 65)  // Fails (< min) / 실패 (최소값 미만)

v := validation.New(70, "age")
v.Between(18, 65)  // Fails (> max) / 실패 (최대값 초과)

v := validation.New(18, "age")
v.Between(18, 65)  // Passes (boundary) / 성공 (경계값)

// Percentage validation / 백분율 검증
v := validation.New(percentage, "discount")
v.Between(0, 100)

// Rating validation / 평점 검증
v := validation.New(rating, "rating")
v.Between(1, 5)

// Temperature range / 온도 범위
v := validation.New(temp, "temperature")
v.Between(-20, 50)

func (*Validator) BetweenTime

func (v *Validator) BetweenTime(start, end time.Time) *Validator

BetweenTime validates that the time value is within the given time range (inclusive). Only works with time.Time values. Both start and end boundaries are included.

BetweenTime은 시간 값이 주어진 시간 범위 내에 있는지 검증합니다 (포함). time.Time 값에서만 작동합니다. 시작 및 종료 경계값 모두 포함됩니다.

Parameters / 매개변수:

  • start: The start time of the range (inclusive) 범위의 시작 시간 (포함)
  • end: The end time of the range (inclusive) 범위의 종료 시간 (포함)

Returns / 반환:

  • *Validator: Returns self for method chaining 메서드 체이닝을 위해 자신을 반환

Behavior / 동작:

  • Accepts if start <= time <= end 시작 <= 시간 <= 종료이면 허용
  • Inclusive on both boundaries 양쪽 경계 모두 포함
  • Timezone-aware comparison 시간대 인식 비교
  • Fails if value is not time.Time 값이 time.Time이 아니면 실패

Use Cases / 사용 사례:

  • Date range validation / 날짜 범위 검증
  • Event time slot validation / 이벤트 시간대 검증
  • Business hours validation / 업무 시간 검증
  • Seasonal validation / 계절 검증
  • Booking period validation / 예약 기간 검증

Thread Safety / 스레드 안전성:

  • Thread-safe: No shared state / 스레드 안전: 공유 상태 없음

Performance / 성능:

  • Time complexity: O(1) 시간 복잡도: O(1)
  • Two time comparisons 두 번의 시간 비교

Example / 예제:

// Year 2024 validation / 2024년 검증
start := time.Date(2024, 1, 1, 0, 0, 0, 0, time.UTC)
end := time.Date(2024, 12, 31, 23, 59, 59, 0, time.UTC)
v := validation.New(date, "date")
v.BetweenTime(start, end)  // Must be in 2024

// Business hours (9 AM - 5 PM) / 업무 시간 (오전 9시 - 오후 5시)
start := time.Date(2024, 1, 1, 9, 0, 0, 0, time.Local)
end := time.Date(2024, 1, 1, 17, 0, 0, 0, time.Local)
v := validation.New(appointmentTime, "appointment")
v.BetweenTime(start, end)

// Boundaries included / 경계값 포함
start := time.Date(2024, 1, 1, 0, 0, 0, 0, time.UTC)
end := time.Date(2024, 1, 31, 0, 0, 0, 0, time.UTC)
v := validation.New(start, "date")
v.BetweenTime(start, end)  // Passes (start included)

v := validation.New(end, "date")
v.BetweenTime(start, end)  // Passes (end included)
Example

ExampleValidator_BetweenTime demonstrates time range validation. ExampleValidator_BetweenTime는 시간 범위 검증을 보여줍니다.

package main

import (
	"fmt"
	"time"

	"github.com/arkd0ng/go-utils/validation"
)

func main() {
	// Define the valid time range for 2024
	start := time.Date(2024, 1, 1, 0, 0, 0, 0, time.UTC)
	end := time.Date(2024, 12, 31, 23, 59, 59, 0, time.UTC)

	// Validate a date within the range
	eventDate := time.Date(2024, 6, 15, 12, 0, 0, 0, time.UTC)
	v := validation.New(eventDate, "event_date")
	v.BetweenTime(start, end)

	err := v.Validate()
	if err != nil {
		fmt.Println("Date is out of range")
	} else {
		fmt.Println("Date is within 2024")
	}
}
Output:

Date is within 2024

func (*Validator) CIDR

func (v *Validator) CIDR() *Validator

CIDR validates that the value is a valid CIDR notation. CIDR format is <IP>/<prefix> for network address representation.

CIDR는 값이 유효한 CIDR 표기법인지 검증합니다. CIDR 형식은 네트워크 주소 표현을 위한 <IP>/<접두사>입니다.

Parameters / 매개변수:

  • None (operates on validator's value) 없음 (validator의 값에 대해 작동)

Returns / 반환:

  • *Validator: Returns self for method chaining 메서드 체이닝을 위해 자신을 반환

Behavior / 동작:

  • Uses net.ParseCIDR for validation 검증을 위해 net.ParseCIDR 사용
  • Accepts IPv4 CIDR (0-32 prefix) IPv4 CIDR 허용 (0-32 접두사)
  • Accepts IPv6 CIDR (0-128 prefix) IPv6 CIDR 허용 (0-128 접두사)
  • Validates both IP and prefix IP와 접두사 모두 검증
  • Fails if format is invalid 형식이 무효하면 실패
  • Fails if value is not string 값이 문자열이 아니면 실패

Use Cases / 사용 사례:

  • Network configuration / 네트워크 구성
  • Subnet validation / 서브넷 검증
  • Firewall rule definition / 방화벽 규칙 정의
  • IP range specification / IP 범위 지정

Thread Safety / 스레드 안전성:

  • Thread-safe: No shared state / 스레드 안전: 공유 상태 없음

Performance / 성능:

  • Time complexity: O(n), n = string length 시간 복잡도: O(n), n = 문자열 길이
  • Single net.ParseCIDR call 단일 net.ParseCIDR 호출

CIDR format is <IP>/<prefix> where / CIDR 형식은 다음과 같습니다: - IP can be IPv4 or IPv6 - prefix must be valid for the IP version (0-32 for IPv4, 0-128 for IPv6)

Example / 예제:

// IPv4 CIDR / IPv4 CIDR
v := validation.New("192.168.1.0/24", "network")
v.CIDR()  // Passes

v = validation.New("10.0.0.0/8", "private_network")
v.CIDR()  // Passes

v = validation.New("172.16.0.0/12", "subnet")
v.CIDR()  // Passes

// IPv6 CIDR / IPv6 CIDR
v = validation.New("2001:db8::/32", "network")
v.CIDR()  // Passes

v = validation.New("fe80::/10", "link_local")
v.CIDR()  // Passes

// Invalid CIDR / 무효한 CIDR
v = validation.New("192.168.1.0/33", "network")
v.CIDR()  // Fails (prefix > 32 for IPv4)

v = validation.New("192.168.1.1", "ip")
v.CIDR()  // Fails (missing prefix)
Example

ExampleValidator_CIDR demonstrates the CIDR validator ExampleValidator_CIDR는 CIDR 검증기를 보여줍니다

package main

import (
	"fmt"

	"github.com/arkd0ng/go-utils/validation"
)

func main() {
	v := validation.New("192.168.1.0/24", "network")
	v.CIDR()
	err := v.Validate()
	if err != nil {
		fmt.Println("Invalid CIDR notation")
	} else {
		fmt.Println("Valid CIDR notation")
	}
}
Output:

Valid CIDR notation

func (*Validator) Contains

func (v *Validator) Contains(substring string) *Validator

Contains validates that the string contains the given substring. Case-sensitive search.

Contains는 문자열이 주어진 부분 문자열을 포함하는지 검증합니다. 대소문자를 구분합니다.

Parameters / 매개변수:

  • substring: The string that must be found within the value 값 내에서 찾아야 하는 문자열

Returns / 반환:

  • *Validator: Returns self for method chaining 메서드 체이닝을 위해 자신을 반환

Behavior / 동작:

  • Case-sensitive search 대소문자 구분 검색
  • Uses strings.Contains() internally 내부적으로 strings.Contains() 사용
  • Empty substring always passes 빈 부분 문자열은 항상 통과
  • Finds substring at any position 어느 위치에서든 부분 문자열 찾기
  • Skips validation if value is not a string 값이 문자열이 아니면 검증 건너뜀

Use Cases / 사용 사례:

  • Keyword filtering / 키워드 필터링
  • Content validation / 콘텐츠 검증
  • Required text presence / 필수 텍스트 존재
  • Substring matching / 부분 문자열 매칭

Thread Safety / 스레드 안전성:

  • Thread-safe: No shared state / 스레드 안전: 공유 상태 없음

Performance / 성능:

  • Time complexity: O(n*m) where n is string length, m is substring length 시간 복잡도: O(n*m) (n은 문자열 길이, m은 부분 문자열 길이)
  • Uses Boyer-Moore-like algorithm internally 내부적으로 Boyer-Moore 유사 알고리즘 사용

Example / 예제:

v := validation.New("Hello World", "message")
v.Contains("World")  // Passes / 성공

v := validation.New("Hello World", "message")
v.Contains("world")  // Fails (case mismatch) / 실패 (대소문자 불일치)

v := validation.New("user@example.com", "email")
v.Contains("@")  // Passes / 성공

// Keyword validation / 키워드 검증
v := validation.New(description, "description")
v.Required().Contains("important").MinLength(10)

// Multiple keywords (need separate validators) / 여러 키워드 (별도 검증기 필요)
v1 := validation.New(text, "content").Contains("keyword1")
v2 := validation.New(text, "content").Contains("keyword2")

func (*Validator) Coordinate

func (v *Validator) Coordinate() *Validator

Coordinate validates coordinate string in "lat,lon" format. Parses and validates both latitude and longitude from comma-separated string.

Coordinate는 "lat,lon" 형식의 좌표 문자열을 검증합니다. 쉼표로 구분된 문자열에서 위도와 경도를 모두 파싱하고 검증합니다.

Parameters / 매개변수:

  • None (operates on validator's value) 없음 (validator의 값에 대해 작동)

Returns / 반환:

  • *Validator: Returns self for method chaining 메서드 체이닝을 위해 자신을 반환

Behavior / 동작:

  • Format: "lat,lon" or "lat, lon" (spaces allowed) 형식: "lat,lon" 또는 "lat, lon" (공백 허용)
  • Trims whitespace around values 값 주변 공백 제거
  • Validates latitude range: -90 to 90 위도 범위 검증: -90 ~ 90
  • Validates longitude range: -180 to 180 경도 범위 검증: -180 ~ 180
  • Fails if not string or invalid format 문자열이 아니거나 형식이 무효하면 실패

Use Cases / 사용 사례:

  • GPS data validation / GPS 데이터 검증
  • Location string parsing / 위치 문자열 파싱
  • Map URL parameters / 지도 URL 매개변수
  • Geolocation API input / 지오로케이션 API 입력

Thread Safety / 스레드 안전성:

  • Thread-safe: No shared state / 스레드 안전: 공유 상태 없음

Performance / 성능:

  • Time complexity: O(n), n = string length 시간 복잡도: O(n), n = 문자열 길이
  • String split + 2 float parses + 2 range checks 문자열 분할 + 2번의 float 파싱 + 2번의 범위 확인

Accepts formats: "lat,lon" or "lat, lon" (with optional space) 허용 형식: "lat,lon" 또는 "lat, lon" (선택적 공백 포함)

Example / 예시:

// Seoul coordinates / 서울 좌표
v := validation.New("37.5665,126.9780", "location")
v.Coordinate()  // Passes

// With spaces / 공백 포함
v = validation.New("37.5665, 126.9780", "location")
v.Coordinate()  // Passes

// Negative coordinates / 음수 좌표
v = validation.New("-33.8688,151.2093", "location")
v.Coordinate()  // Passes (Sydney)

// Boundaries / 경계값
v = validation.New("90,180", "location")
v.Coordinate()  // Passes

// Invalid - missing longitude / 무효 - 경도 누락
v = validation.New("37.5665", "location")
v.Coordinate()  // Fails

// Invalid - out of range / 무효 - 범위 밖
v = validation.New("95,126", "location")
v.Coordinate()  // Fails (lat > 90)
Example

ExampleValidator_Coordinate demonstrates coordinate string validation ExampleValidator_Coordinate는 좌표 문자열 검증을 보여줍니다

package main

import (
	"fmt"

	"github.com/arkd0ng/go-utils/validation"
)

func main() {
	v := validation.New("37.5665,126.9780", "location")
	v.Coordinate()

	if len(v.GetErrors()) > 0 {
		fmt.Println("Invalid coordinate")
	} else {
		fmt.Println("Valid coordinate")
	}
}
Output:

Valid coordinate

func (*Validator) CreditCard

func (v *Validator) CreditCard() *Validator

CreditCard validates that the value is a valid credit card number using the Luhn algorithm. Accepts numbers with spaces or hyphens, validates length (13-19 digits), and performs checksum verification.

CreditCard는 Luhn 알고리즘을 사용하여 값이 유효한 신용카드 번호인지 검증합니다. 공백이나 하이픈이 포함된 번호를 허용하고, 길이(13-19자리)를 검증하며, 체크섬 확인을 수행합니다.

Parameters / 매개변수:

  • None (operates on validator's value) 없음 (validator의 값에 대해 작동)

Returns / 반환:

  • *Validator: Returns self for method chaining 메서드 체이닝을 위해 자신을 반환

Behavior / 동작:

  • Removes spaces and hyphens before validation 검증 전에 공백과 하이픈 제거
  • Accepts only numeric characters 숫자만 허용
  • Validates length: 13-19 digits (standard card length) 길이 검증: 13-19자리 (표준 카드 길이)
  • Applies Luhn algorithm checksum validation Luhn 알고리즘 체크섬 검증 적용
  • Fails if value is not string 값이 문자열이 아니면 실패

Use Cases / 사용 사례:

  • Payment form validation / 결제 양식 검증
  • Credit card input validation / 신용카드 입력 검증
  • Card number format verification / 카드 번호 형식 확인
  • E-commerce checkout validation / 전자상거래 체크아웃 검증

Thread Safety / 스레드 안전성:

  • Thread-safe: No shared state / 스레드 안전: 공유 상태 없음

Performance / 성능:

  • Time complexity: O(n), n = number length 시간 복잡도: O(n), n = 번호 길이
  • Single pass Luhn algorithm 단일 패스 Luhn 알고리즘

Example / 예제:

// Valid card numbers / 유효한 카드 번호
v := validation.New("4532015112830366", "card")
v.CreditCard()  // Passes (valid Visa)

// With formatting / 형식 포함
v = validation.New("4532-0151-1283-0366", "card")
v.CreditCard()  // Passes (hyphens removed)

v = validation.New("4532 0151 1283 0366", "card")
v.CreditCard()  // Passes (spaces removed)

// Invalid checksum / 무효한 체크섬
v = validation.New("4532015112830367", "card")
v.CreditCard()  // Fails (Luhn check fails)

// Invalid length / 무효한 길이
v = validation.New("123", "card")
v.CreditCard()  // Fails (too short)
Example

ExampleValidator_CreditCard demonstrates credit card validation ExampleValidator_CreditCard는 신용카드 검증을 보여줍니다

package main

import (
	"fmt"

	"github.com/arkd0ng/go-utils/validation"
)

func main() {
	v := validation.New("4532015112830366", "card_number")
	v.CreditCard()

	if len(v.GetErrors()) > 0 {
		fmt.Println("Invalid credit card")
	} else {
		fmt.Println("Valid credit card")
	}
}
Output:

Valid credit card

func (*Validator) CreditCardType

func (v *Validator) CreditCardType(cardType string) *Validator

CreditCardType validates that the value is a valid credit card number of the specified type. Checks card-specific patterns and applies Luhn algorithm verification.

CreditCardType는 값이 지정된 타입의 유효한 신용카드 번호인지 검증합니다. 카드별 패턴을 확인하고 Luhn 알고리즘 검증을 적용합니다.

Parameters / 매개변수:

  • cardType: Card type to validate (visa, mastercard, amex, discover, jcb, dinersclub, unionpay) 검증할 카드 타입 (visa, mastercard, amex, discover, jcb, dinersclub, unionpay)

Returns / 반환:

  • *Validator: Returns self for method chaining 메서드 체이닝을 위해 자신을 반환

Behavior / 동작:

  • Removes spaces and hyphens before validation 검증 전에 공백과 하이픈 제거
  • Case-insensitive card type matching 대소문자 구분 없는 카드 타입 매칭
  • Validates card-specific patterns: 카드별 패턴 검증:
  • Visa: Starts with 4, 13 or 16 digits
  • MasterCard: Starts with 51-55, 16 digits
  • Amex: Starts with 34 or 37, 15 digits
  • Discover: Starts with 6011 or 65, 16 digits
  • JCB: Starts with 2131, 1800, or 35, 16 digits
  • Diners Club: Starts with 300-305 or 36/38, 14 digits
  • UnionPay: Starts with 62, 16-19 digits
  • Applies Luhn algorithm after pattern check 패턴 확인 후 Luhn 알고리즘 적용
  • Fails if card type unknown 카드 타입이 알 수 없으면 실패
  • Fails if value is not string 값이 문자열이 아니면 실패

Use Cases / 사용 사례:

  • Card type-specific validation / 카드 타입별 검증
  • Payment processor integration / 결제 처리 통합
  • Card brand detection / 카드 브랜드 감지
  • Merchant-specific card acceptance / 가맹점별 카드 수용

Thread Safety / 스레드 안전성:

  • Thread-safe: No shared state / 스레드 안전: 공유 상태 없음

Performance / 성능:

  • Time complexity: O(n), n = number length 시간 복잡도: O(n), n = 번호 길이
  • Single regex match + Luhn check 단일 정규식 매칭 + Luhn 확인

Example / 예제:

// Visa card validation / Visa 카드 검증
v := validation.New("4532015112830366", "card")
v.CreditCardType("visa")  // Passes

// Mastercard validation / Mastercard 검증
v = validation.New("5425233430109903", "card")
v.CreditCardType("mastercard")  // Passes

// American Express / American Express
v = validation.New("374245455400126", "card")
v.CreditCardType("amex")  // Passes

// Wrong type / 잘못된 타입
v = validation.New("4532015112830366", "card")
v.CreditCardType("mastercard")  // Fails (Visa card)

// Case-insensitive / 대소문자 구분 없음
v = validation.New("4532015112830366", "card")
v.CreditCardType("VISA")  // Passes
Example

ExampleValidator_CreditCardType demonstrates credit card type validation ExampleValidator_CreditCardType는 신용카드 타입 검증을 보여줍니다

package main

import (
	"fmt"

	"github.com/arkd0ng/go-utils/validation"
)

func main() {
	v := validation.New("4532015112830366", "card_number")
	v.CreditCardType("visa")

	if len(v.GetErrors()) > 0 {
		fmt.Println("Invalid Visa card")
	} else {
		fmt.Println("Valid Visa card")
	}
}
Output:

Valid Visa card

func (*Validator) Custom

func (v *Validator) Custom(fn RuleFunc, message string) *Validator

Custom applies a custom validation function with a message. Custom은 사용자 정의 검증 함수를 메시지와 함께 적용합니다.

Example

ExampleValidator_Custom demonstrates the Custom validator ExampleValidator_Custom는 Custom 검증기를 보여줍니다

package main

import (
	"fmt"

	"github.com/arkd0ng/go-utils/validation"
)

func main() {
	v := validation.New("password123", "password")
	v.Custom(func(val interface{}) bool {
		str, ok := val.(string)
		if !ok {
			return false
		}
		// Check if password contains numbers
		for _, ch := range str {
			if ch >= '0' && ch <= '9' {
				return true
			}
		}
		return false
	}, "password must contain at least one number")
	err := v.Validate()
	if err != nil {
		fmt.Println("Invalid password")
	} else {
		fmt.Println("Valid password")
	}
}
Output:

Valid password

func (*Validator) DateAfter

func (v *Validator) DateAfter(after time.Time) *Validator

DateAfter validates that the date value is after the specified date. Accepts time.Time objects or date strings in RFC3339/ISO 8601 formats.

DateAfter는 날짜 값이 지정된 날짜 이후인지 검증합니다. time.Time 객체 또는 RFC3339/ISO 8601 형식의 날짜 문자열을 허용합니다.

Parameters / 매개변수:

  • after: Minimum date (exclusive) 최소 날짜 (제외)

Returns / 반환:

  • *Validator: Returns self for method chaining 메서드 체이닝을 위해 자신을 반환

Behavior / 동작:

  • Accepts time.Time objects directly time.Time 객체 직접 허용
  • Accepts string in RFC3339 format ("2006-01-02T15:04:05Z07:00") RFC3339 형식 문자열 허용 ("2006-01-02T15:04:05Z07:00")
  • Accepts string in ISO 8601 format ("2006-01-02") ISO 8601 형식 문자열 허용 ("2006-01-02")
  • Tries RFC3339 first, then ISO 8601 RFC3339 먼저 시도, 그 다음 ISO 8601
  • Exclusive comparison (equal dates fail) 배타적 비교 (같은 날짜는 실패)
  • Fails if value is not supported type 값이 지원되지 않는 타입이면 실패
  • Fails if string parsing fails 문자열 파싱 실패 시 실패

Use Cases / 사용 사례:

  • Start date validation / 시작 날짜 검증
  • Minimum date constraint / 최소 날짜 제약
  • Future date validation / 미래 날짜 검증
  • Date range lower bound / 날짜 범위 하한

Thread Safety / 스레드 안전성:

  • Thread-safe: No shared state / 스레드 안전: 공유 상태 없음

Performance / 성능:

  • Time complexity: O(n) for string parsing, O(1) for time.Time 시간 복잡도: 문자열 파싱 O(n), time.Time O(1)
  • Up to 2 parse attempts for strings 문자열에 대해 최대 2번의 파싱 시도

The value can be / 값은 다음이 될 수 있음:

  • time.Time object
  • string in RFC3339 format ("2006-01-02T15:04:05Z07:00")
  • string in ISO 8601 format ("2006-01-02")

Example / 예제:

// time.Time validation / time.Time 검증
minDate := time.Date(2025, 1, 1, 0, 0, 0, 0, time.UTC)
userDate := time.Date(2025, 6, 15, 0, 0, 0, 0, time.UTC)
v := validation.New(userDate, "start_date")
v.DateAfter(minDate)  // Passes

// ISO 8601 string / ISO 8601 문자열
v = validation.New("2025-06-15", "date")
v.DateAfter(minDate)  // Passes

// RFC3339 string / RFC3339 문자열
v = validation.New("2025-06-15T10:30:00Z", "datetime")
v.DateAfter(minDate)  // Passes

// Equal date fails / 같은 날짜는 실패
v = validation.New(minDate, "date")
v.DateAfter(minDate)  // Fails (not after)

err := v.Validate()
Example

ExampleValidator_DateAfter demonstrates date after validation ExampleValidator_DateAfter는 날짜 이후 검증을 보여줍니다

package main

import (
	"fmt"
	"time"

	"github.com/arkd0ng/go-utils/validation"
)

func main() {
	minDate := time.Date(2025, 1, 1, 0, 0, 0, 0, time.UTC)
	testDate := time.Date(2025, 10, 17, 12, 0, 0, 0, time.UTC)

	v := validation.New(testDate, "start_date")
	v.DateAfter(minDate)
	err := v.Validate()
	if err != nil {
		fmt.Println("Date is not after min date")
	} else {
		fmt.Println("Date is after min date")
	}
}
Output:

Date is after min date

func (*Validator) DateBefore

func (v *Validator) DateBefore(before time.Time) *Validator

DateBefore validates that the date value is before the specified date. Accepts time.Time objects or date strings in RFC3339/ISO 8601 formats.

DateBefore는 날짜 값이 지정된 날짜 이전인지 검증합니다. time.Time 객체 또는 RFC3339/ISO 8601 형식의 날짜 문자열을 허용합니다.

Parameters / 매개변수:

  • before: Maximum date (exclusive) 최대 날짜 (제외)

Returns / 반환:

  • *Validator: Returns self for method chaining 메서드 체이닝을 위해 자신을 반환

Behavior / 동작:

  • Accepts time.Time objects directly time.Time 객체 직접 허용
  • Accepts string in RFC3339 format ("2006-01-02T15:04:05Z07:00") RFC3339 형식 문자열 허용 ("2006-01-02T15:04:05Z07:00")
  • Accepts string in ISO 8601 format ("2006-01-02") ISO 8601 형식 문자열 허용 ("2006-01-02")
  • Tries RFC3339 first, then ISO 8601 RFC3339 먼저 시도, 그 다음 ISO 8601
  • Exclusive comparison (equal dates fail) 배타적 비교 (같은 날짜는 실패)
  • Fails if value is not supported type 값이 지원되지 않는 타입이면 실패
  • Fails if string parsing fails 문자열 파싱 실패 시 실패

Use Cases / 사용 사례:

  • Expiry date validation / 만료 날짜 검증
  • Maximum date constraint / 최대 날짜 제약
  • Past date validation / 과거 날짜 검증
  • Date range upper bound / 날짜 범위 상한

Thread Safety / 스레드 안전성:

  • Thread-safe: No shared state / 스레드 안전: 공유 상태 없음

Performance / 성능:

  • Time complexity: O(n) for string parsing, O(1) for time.Time 시간 복잡도: 문자열 파싱 O(n), time.Time O(1)
  • Up to 2 parse attempts for strings 문자열에 대해 최대 2번의 파싱 시도

The value can be / 값은 다음이 될 수 있음:

  • time.Time object
  • string in RFC3339 format ("2006-01-02T15:04:05Z07:00")
  • string in ISO 8601 format ("2006-01-02")

Example / 예제:

// time.Time validation / time.Time 검증
maxDate := time.Date(2025, 12, 31, 0, 0, 0, 0, time.UTC)
userDate := time.Date(2025, 6, 15, 0, 0, 0, 0, time.UTC)
v := validation.New(userDate, "expiry_date")
v.DateBefore(maxDate)  // Passes

// ISO 8601 string / ISO 8601 문자열
v = validation.New("2025-06-15", "date")
v.DateBefore(maxDate)  // Passes

// RFC3339 string / RFC3339 문자열
v = validation.New("2025-06-15T10:30:00Z", "datetime")
v.DateBefore(maxDate)  // Passes

// Equal date fails / 같은 날짜는 실패
v = validation.New(maxDate, "date")
v.DateBefore(maxDate)  // Fails (not before)

err := v.Validate()
Example

ExampleValidator_DateBefore demonstrates date before validation ExampleValidator_DateBefore는 날짜 이전 검증을 보여줍니다

package main

import (
	"fmt"
	"time"

	"github.com/arkd0ng/go-utils/validation"
)

func main() {
	maxDate := time.Date(2025, 12, 31, 0, 0, 0, 0, time.UTC)
	testDate := time.Date(2025, 10, 17, 12, 0, 0, 0, time.UTC)

	v := validation.New(testDate, "expiry_date")
	v.DateBefore(maxDate)
	err := v.Validate()
	if err != nil {
		fmt.Println("Date is not before max date")
	} else {
		fmt.Println("Date is before max date")
	}
}
Output:

Date is before max date

func (*Validator) DateFormat

func (v *Validator) DateFormat(format string) *Validator

DateFormat validates that the value is a valid date string in the specified format. Uses Go's time.Parse with the provided layout to verify date string validity.

DateFormat은 값이 지정된 형식의 유효한 날짜 문자열인지 검증합니다. 제공된 레이아웃으로 Go의 time.Parse를 사용하여 날짜 문자열 유효성을 확인합니다.

Parameters / 매개변수:

  • format: Go time layout format string Go 시간 레이아웃 형식 문자열

Returns / 반환:

  • *Validator: Returns self for method chaining 메서드 체이닝을 위해 자신을 반환

Behavior / 동작:

  • Uses time.Parse for validation time.Parse를 사용하여 검증
  • Accepts any Go time layout format 모든 Go 시간 레이아웃 형식 허용
  • Common formats: 일반 형식:
  • "2006-01-02" - ISO 8601 date (YYYY-MM-DD)
  • "02/01/2006" - DD/MM/YYYY
  • "01/02/2006" - MM/DD/YYYY
  • "2006/01/02" - YYYY/MM/DD
  • "Jan 2, 2006" - Month Day, Year
  • Fails if value is not string 값이 문자열이 아니면 실패
  • Fails if parsing fails 파싱 실패 시 실패

Use Cases / 사용 사례:

  • Date input validation / 날짜 입력 검증
  • Form date field validation / 양식 날짜 필드 검증
  • Date string format enforcement / 날짜 문자열 형식 적용
  • API date parameter validation / API 날짜 매개변수 검증

Thread Safety / 스레드 안전성:

  • Thread-safe: No shared state / 스레드 안전: 공유 상태 없음

Performance / 성능:

  • Time complexity: O(n), n = string length 시간 복잡도: O(n), n = 문자열 길이
  • Single time.Parse call 단일 time.Parse 호출

Supported formats / 지원 형식:

  • "2006-01-02" (ISO 8601 date)
  • "02/01/2006" (DD/MM/YYYY)
  • "01/02/2006" (MM/DD/YYYY)
  • "2006/01/02" (YYYY/MM/DD)
  • Any valid Go time.Parse format

Example / 예제:

// ISO 8601 format / ISO 8601 형식
v := validation.New("2025-10-17", "birth_date")
v.DateFormat("2006-01-02")  // Passes

// US format / 미국 형식
v = validation.New("10/17/2025", "date")
v.DateFormat("01/02/2006")  // Passes

// European format / 유럽 형식
v = validation.New("17/10/2025", "date")
v.DateFormat("02/01/2006")  // Passes

// Invalid format / 무효한 형식
v = validation.New("2025-10-17", "date")
v.DateFormat("01/02/2006")  // Fails (format mismatch)

err := v.Validate()
Example

ExampleValidator_DateFormat demonstrates date format validation ExampleValidator_DateFormat는 날짜 형식 검증을 보여줍니다

package main

import (
	"fmt"

	"github.com/arkd0ng/go-utils/validation"
)

func main() {
	v := validation.New("2025-10-17", "birth_date")
	v.DateFormat("2006-01-02")
	err := v.Validate()
	if err != nil {
		fmt.Println("Invalid date format")
	} else {
		fmt.Println("Valid date format")
	}
}
Output:

Valid date format

func (*Validator) DateRange

func (v *Validator) DateRange(start, end time.Time) *Validator

DateRange validates that a date value is within the specified date range (inclusive). Accepts time.Time objects or date strings in RFC3339/ISO 8601 formats.

DateRange는 날짜 값이 지정된 날짜 범위 내에 있는지 검증합니다 (포함). time.Time 객체 또는 RFC3339/ISO 8601 형식의 날짜 문자열을 허용합니다.

Parameters / 매개변수:

  • start: Start date (inclusive) 시작 날짜 (포함)
  • end: End date (inclusive) 종료 날짜 (포함)

Returns / 반환:

  • *Validator: Returns self for method chaining 메서드 체이닝을 위해 자신을 반환

Behavior / 동작:

  • Accepts time.Time objects directly time.Time 객체 직접 허용
  • Accepts string in RFC3339 format ("2006-01-02T15:04:05Z07:00") RFC3339 형식 문자열 허용 ("2006-01-02T15:04:05Z07:00")
  • Accepts string in ISO 8601 format ("2006-01-02") ISO 8601 형식 문자열 허용 ("2006-01-02")
  • Tries RFC3339 first, then ISO 8601 RFC3339 먼저 시도, 그 다음 ISO 8601
  • Inclusive range: start <= value <= end 포함 범위: 시작 <= 값 <= 종료
  • Fails if value is not supported type 값이 지원되지 않는 타입이면 실패
  • Fails if string parsing fails 문자열 파싱 실패 시 실패

Use Cases / 사용 사례:

  • Event date validation / 이벤트 날짜 검증
  • Booking period validation / 예약 기간 검증
  • Valid date window / 유효 날짜 창
  • Historical period validation / 역사적 기간 검증

Thread Safety / 스레드 안전성:

  • Thread-safe: No shared state / 스레드 안전: 공유 상태 없음

Performance / 성능:

  • Time complexity: O(n) for string parsing, O(1) for time.Time 시간 복잡도: 문자열 파싱 O(n), time.Time O(1)
  • Up to 2 parse attempts for strings 문자열에 대해 최대 2번의 파싱 시도

The range is inclusive: start <= value <= end

The value can be / 값은 다음이 될 수 있음:

  • time.Time object
  • string in RFC3339 format ("2006-01-02T15:04:05Z07:00")
  • string in ISO 8601 format ("2006-01-02")

Example / 예제:

// Event date range / 이벤트 날짜 범위
start := time.Date(2025, 1, 1, 0, 0, 0, 0, time.UTC)
end := time.Date(2025, 12, 31, 23, 59, 59, 0, time.UTC)
eventDate := time.Date(2025, 6, 15, 0, 0, 0, 0, time.UTC)
v := validation.New(eventDate, "event_date")
v.DateRange(start, end)  // Passes (within 2025)

// ISO 8601 string / ISO 8601 문자열
v = validation.New("2025-06-15", "date")
v.DateRange(start, end)  // Passes

// RFC3339 string / RFC3339 문자열
v = validation.New("2025-06-15T10:30:00Z", "datetime")
v.DateRange(start, end)  // Passes

// Boundaries included / 경계값 포함
v = validation.New(start, "date")
v.DateRange(start, end)  // Passes (start included)

v = validation.New(end, "date")
v.DateRange(start, end)  // Passes (end included)

// Out of range / 범위 밖
v = validation.New("2024-12-31", "date")
v.DateRange(start, end)  // Fails (before start)

err := v.Validate()
Example

ExampleValidator_DateRange demonstrates date range validation ExampleValidator_DateRange는 날짜 범위 검증을 보여줍니다

package main

import (
	"fmt"
	"time"

	"github.com/arkd0ng/go-utils/validation"
)

func main() {
	start := time.Date(2025, 1, 1, 0, 0, 0, 0, time.UTC)
	end := time.Date(2025, 12, 31, 23, 59, 59, 0, time.UTC)
	testDate := time.Date(2025, 6, 15, 12, 0, 0, 0, time.UTC)

	v := validation.New(testDate, "event_date")
	v.DateRange(start, end)
	err := v.Validate()
	if err != nil {
		fmt.Println("Date is out of range")
	} else {
		fmt.Println("Date is within range")
	}
}
Output:

Date is within range

func (*Validator) EAN

func (v *Validator) EAN() *Validator

EAN validates European Article Number (EAN-8 or EAN-13). Validates product barcodes with checksum verification.

EAN는 유럽 상품 코드(EAN-8 또는 EAN-13)를 검증합니다. 체크섬 확인과 함께 상품 바코드를 검증합니다.

Parameters / 매개변수:

  • None (operates on validator's value) 없음 (validator의 값에 대해 작동)

Returns / 반환:

  • *Validator: Returns self for method chaining 메서드 체이닝을 위해 자신을 반환

Behavior / 동작:

  • Supports EAN-8 (8 digits) EAN-8 지원 (8자리)
  • Supports EAN-13 (13 digits) EAN-13 지원 (13자리)
  • Allows hyphens and spaces (removed for validation) 하이픈 및 공백 허용 (검증 시 제거)
  • Validates checksum using EAN algorithm EAN 알고리즘을 사용한 체크섬 검증

Use Cases / 사용 사례:

  • Retail product scanning / 소매 상품 스캔
  • Inventory management / 재고 관리
  • Point of sale systems / 판매 시점 시스템
  • E-commerce product identification / 전자상거래 상품 식별

Thread Safety / 스레드 안전성:

  • Thread-safe: No shared state / 스레드 안전: 공유 상태 없음

Performance / 성능:

  • Time complexity: O(n), n = 8 or 13 시간 복잡도: O(n), n = 8 또는 13
  • Checksum calculation required 체크섬 계산 필요

Supports both EAN-8 and EAN-13 formats with checksum validation. 체크섬 검증과 함께 EAN-8 및 EAN-13 형식을 모두 지원합니다.

Example / 예시:

// Valid EAN-13 / 유효한 EAN-13
v := validation.New("4006381333931", "ean")
v.EAN()  // Passes

// Valid EAN-8 / 유효한 EAN-8
v = validation.New("96385074", "ean")
v.EAN()  // Passes

// With spaces / 공백 포함
v = validation.New("4006381 333931", "ean")
v.EAN()  // Passes

// Invalid checksum / 무효한 체크섬
v = validation.New("4006381333930", "ean")
v.EAN()  // Fails

// Invalid length / 무효한 길이
v = validation.New("123456", "ean")
v.EAN()  // Fails (not 8 or 13 digits)

Validation rules / 검증 규칙:

  • Must be a string / 문자열이어야 함
  • Must be 8 or 13 digits (excluding hyphens/spaces) / 8 또는 13자리 (하이픈/공백 제외)
  • Must pass checksum validation / 체크섬 검증 통과
Example

ExampleValidator_EAN demonstrates EAN validation ExampleValidator_EAN는 EAN 검증을 보여줍니다

package main

import (
	"fmt"

	"github.com/arkd0ng/go-utils/validation"
)

func main() {
	v := validation.New("4006381333931", "ean")
	v.EAN()

	if len(v.GetErrors()) > 0 {
		fmt.Println("Invalid EAN")
	} else {
		fmt.Println("Valid EAN")
	}
}
Output:

Valid EAN

func (*Validator) Email

func (v *Validator) Email() *Validator

Email validates that the string is a valid email address format. It uses a regex pattern that covers most common email formats per RFC 5322.

Email은 문자열이 유효한 이메일 주소 형식인지 검증합니다. RFC 5322에 따라 대부분의 일반적인 이메일 형식을 다루는 정규식 패턴을 사용합니다.

Format Rules / 형식 규칙:

  • Local part: alphanumeric, dots, underscores, percent, plus, hyphen 로컬 부분: 영숫자, 점, 언더스코어, 퍼센트, 플러스, 하이픈
  • @ symbol required / @ 기호 필수
  • Domain: alphanumeric, dots, hyphen 도메인: 영숫자, 점, 하이픈
  • TLD: at least 2 letters 최상위 도메인: 최소 2글자

Valid Examples / 유효한 예:

  • user@example.com
  • john.doe@company.co.uk
  • test+tag@domain.com
  • user_123@sub.domain.com

Invalid Examples / 유효하지 않은 예:

  • missing@domain (no TLD)
  • @example.com (no local part)
  • user@.com (invalid domain)
  • user..name@example.com (consecutive dots)

Behavior / 동작:

  • Case-insensitive validation 대소문자 구분 없는 검증
  • Does not validate if email actually exists 이메일이 실제로 존재하는지는 검증하지 않음
  • Skips validation if value is not a string 값이 문자열이 아니면 검증 건너뜀

Thread Safety / 스레드 안전성:

  • Thread-safe: Uses compiled regex (safe for concurrent use) 스레드 안전: 컴파일된 정규식 사용 (동시 사용 안전)

Performance / 성능:

  • Time complexity: O(n) where n is string length 시간 복잡도: O(n) (n은 문자열 길이)
  • Regex is pre-compiled for efficiency 효율성을 위해 정규식 사전 컴파일됨

Limitations / 제한사항:

  • Simplified regex, may not catch all edge cases 간소화된 정규식, 모든 엣지 케이스를 잡지 못할 수 있음
  • International domain names (IDN) need special handling 국제 도메인 이름(IDN)은 특별한 처리 필요

Example / 예제:

v := validation.New("user@example.com", "email")
v.Email()  // Passes / 성공

v := validation.New("invalid-email", "email")
v.Email()  // Fails / 실패

// Chaining with other validations / 다른 검증과 체이닝
v := validation.New(email, "email")
v.Required().Email().MaxLength(100)
Example

ExampleValidator_Email demonstrates the Email validator ExampleValidator_Email는 Email 검증기를 보여줍니다

package main

import (
	"fmt"

	"github.com/arkd0ng/go-utils/validation"
)

func main() {
	v := validation.New("user@example.com", "email")
	v.Email()
	err := v.Validate()
	if err != nil {
		fmt.Println("Invalid email")
	} else {
		fmt.Println("Valid email")
	}
}
Output:

Valid email

func (*Validator) Empty

func (v *Validator) Empty() *Validator

Empty validates that the value is empty (zero value). Checks for zero values based on type: "", 0, false, nil, empty slices/maps.

Empty는 값이 비어있는지 (제로 값) 검증합니다. 타입에 따른 제로 값 확인: "", 0, false, nil, 빈 슬라이스/맵.

Parameters / 매개변수:

  • None (operates on validator's value) 없음 (validator의 값에 대해 작동)

Returns / 반환:

  • *Validator: Returns self for method chaining 메서드 체이닝을 위해 자신을 반환

Behavior / 동작:

  • String: empty string "" 문자열: 빈 문자열 ""
  • Numbers: 0 숫자: 0
  • Boolean: false 불리언: false
  • Slice/Map: nil or length 0 슬라이스/맵: nil 또는 길이 0
  • Pointer: nil 포인터: nil

Use Cases / 사용 사례:

  • Optional field check / 선택적 필드 확인
  • Default value validation / 기본값 검증
  • Uninitialized state check / 초기화되지 않은 상태 확인
  • Zero value detection / 제로 값 감지

Thread Safety / 스레드 안전성:

  • Thread-safe: No shared state / 스레드 안전: 공유 상태 없음

Performance / 성능:

  • Time complexity: O(1) for most types 시간 복잡도: 대부분 타입에서 O(1)
  • Reflection-based type switch 리플렉션 기반 타입 스위치

This validator checks if the value is the zero value for its type: - string: "" - numbers: 0 - bool: false - slice/map: nil or len == 0 - pointer: nil 이 검증기는 값이 해당 타입의 제로 값인지 확인합니다: - 문자열: "" - 숫자: 0 - 불리언: false - 슬라이스/맵: nil 또는 len == 0 - 포인터: nil

Example / 예시:

// Valid empty string / 유효한 빈 문자열
value := ""
v := validation.New(value, "optional")
v.Empty()  // Passes

// Valid zero number / 유효한 제로 숫자
v = validation.New(0, "count")
v.Empty()  // Passes

// Valid false boolean / 유효한 false 불리언
v = validation.New(false, "flag")
v.Empty()  // Passes

// Invalid - non-empty / 무효 - 비어있지 않음
v = validation.New("hello", "text")
v.Empty()  // Fails

Validation rules / 검증 규칙:

  • Value must be zero value for its type / 값이 해당 타입의 제로 값이어야 함
Example

ExampleValidator_Empty demonstrates empty value validation. ExampleValidator_Empty는 빈 값 검증을 보여줍니다.

package main

import (
	"fmt"

	"github.com/arkd0ng/go-utils/validation"
)

func main() {
	// Validate optional field is empty
	optionalField := ""
	v := validation.New(optionalField, "optional_field")
	v.Empty()

	err := v.Validate()
	if err != nil {
		fmt.Println("Field should be empty")
	} else {
		fmt.Println("Field is empty as expected")
	}
}
Output:

Field is empty as expected

func (*Validator) EndsWith

func (v *Validator) EndsWith(suffix string) *Validator

EndsWith validates that the string ends with the given suffix. Case-sensitive comparison.

EndsWith는 문자열이 주어진 접미사로 끝나는지 검증합니다. 대소문자를 구분합니다.

Parameters / 매개변수:

  • suffix: The string that must appear at the end 끝 부분에 나타나야 하는 문자열

Returns / 반환:

  • *Validator: Returns self for method chaining 메서드 체이닝을 위해 자신을 반환

Behavior / 동작:

  • Case-sensitive comparison 대소문자 구분 비교
  • Uses strings.HasSuffix() internally 내부적으로 strings.HasSuffix() 사용
  • Empty suffix always passes 빈 접미사는 항상 통과
  • Skips validation if value is not a string 값이 문자열이 아니면 검증 건너뜀

Use Cases / 사용 사례:

  • File extension validation (.jpg, .pdf, .txt) 파일 확장자 검증 (.jpg, .pdf, .txt)
  • Domain validation (.com, .org, .net) 도메인 검증 (.com, .org, .net)
  • Email domain restriction (@company.com) 이메일 도메인 제한 (@company.com)
  • Code/ID suffix requirements (_TEST, _PROD) 코드/ID 접미사 요구사항 (_TEST, _PROD)

Thread Safety / 스레드 안전성:

  • Thread-safe: No shared state / 스레드 안전: 공유 상태 없음

Performance / 성능:

  • Time complexity: O(n) where n is suffix length 시간 복잡도: O(n) (n은 접미사 길이)
  • Optimal performance for suffix checking 접미사 검사에 최적의 성능

Example / 예제:

v := validation.New("document.pdf", "filename")
v.EndsWith(".pdf")  // Passes / 성공

v := validation.New("document.txt", "filename")
v.EndsWith(".pdf")  // Fails / 실패

v := validation.New("user@company.com", "email")
v.EndsWith("@company.com")  // Passes / 성공

// File extension validation / 파일 확장자 검증
v := validation.New(filename, "upload")
v.Required().EndsWith(".jpg")

// Multiple allowed extensions / 여러 허용 확장자
filename := "image.png"
if !strings.HasSuffix(filename, ".jpg") && !strings.HasSuffix(filename, ".png") {
    // validation fails / 검증 실패
}

// Case sensitivity / 대소문자 구분
v := validation.New("FILE.PDF", "filename")
v.EndsWith(".pdf")  // Fails (case mismatch) / 실패 (대소문자 불일치)

func (*Validator) Equals

func (v *Validator) Equals(value interface{}) *Validator

Equals validates that the value is exactly equal to the given value. Uses Go's == operator for comparison, supporting all comparable types.

Equals는 값이 주어진 값과 정확히 같은지 검증합니다. 비교 가능한 모든 타입을 지원하는 Go의 == 연산자를 사용합니다.

Parameters / 매개변수:

  • value: The expected value to compare against 비교할 기대값

Returns / 반환:

  • *Validator: Returns self for method chaining 메서드 체이닝을 위해 자신을 반환

Behavior / 동작:

  • Uses == operator for comparison 비교에 == 연산자 사용
  • Type-sensitive comparison (5 != "5") 타입 구분 비교 (5 != "5")
  • Case-sensitive for strings 문자열은 대소문자 구분
  • Exact match required 정확한 일치 필요

Use Cases / 사용 사례:

  • Password confirmation / 비밀번호 확인
  • Exact value validation / 정확한 값 검증
  • Field matching validation / 필드 일치 검증
  • Expected value checks / 예상 값 확인
  • Agreement/consent validation / 동의/승인 검증

Thread Safety / 스레드 안전성:

  • Thread-safe: No shared state / 스레드 안전: 공유 상태 없음

Performance / 성능:

  • Time complexity: O(1) for primitive types 시간 복잡도: 기본 타입의 경우 O(1)
  • Direct comparison, very fast 직접 비교, 매우 빠름

Limitations / 제한사항:

  • Not suitable for complex type comparison (use reflect.DeepEqual instead) 복잡한 타입 비교에는 부적합 (대신 reflect.DeepEqual 사용)
  • Slice/map/struct comparison may not work as expected 슬라이스/맵/구조체 비교는 예상대로 작동하지 않을 수 있음

Example / 예제:

// Password confirmation / 비밀번호 확인
v := validation.New("password123", "confirm_password")
v.Equals(originalPassword)  // Must match exactly

// Exact string match / 정확한 문자열 일치
v := validation.New("admin", "role")
v.Equals("admin")  // Passes / 성공

// Numeric equality / 숫자 동등성
v := validation.New(42, "answer")
v.Equals(42)  // Passes / 성공

// Case-sensitive / 대소문자 구분
v := validation.New("Admin", "role")
v.Equals("admin")  // Fails / 실패

// Type-sensitive / 타입 구분
v := validation.New(5, "number")
v.Equals("5")  // Fails (different types) / 실패 (다른 타입)
Example

ExampleValidator_Equals demonstrates the Equals validator ExampleValidator_Equals는 Equals 검증기를 보여줍니다

package main

import (
	"fmt"

	"github.com/arkd0ng/go-utils/validation"
)

func main() {
	v := validation.New(100, "value")
	v.Equals(100)
	err := v.Validate()
	if err != nil {
		fmt.Println("Values not equal")
	} else {
		fmt.Println("Values are equal")
	}
}
Output:

Values are equal

func (*Validator) Even

func (v *Validator) Even() *Validator

Even validates that the numeric value is an even number (divisible by 2). Converts to integer before checking, so decimal parts are truncated.

Even은 숫자 값이 짝수(2로 나누어떨어짐)인지 검증합니다. 검사 전 정수로 변환하므로 소수 부분은 버려집니다.

Returns / 반환:

  • *Validator: Returns self for method chaining 메서드 체이닝을 위해 자신을 반환

Behavior / 동작:

  • Converts value to int before checking 검사 전 int로 변환
  • Truncates decimal part (2.9 becomes 2) 소수 부분 버림 (2.9는 2가 됨)
  • Uses modulo operation: val % 2 == 0 나머지 연산 사용: val % 2 == 0
  • Zero is considered even 0은 짝수로 간주
  • Negative even numbers are valid (-2, -4, etc.) 음수 짝수도 유효 (-2, -4 등)
  • Skips validation if value is not numeric 값이 숫자가 아니면 검증 건너뜀

Use Cases / 사용 사례:

  • Even number requirements / 짝수 요구사항
  • Pair-based calculations / 쌍 기반 계산
  • Alternating patterns / 교대 패턴
  • Divisibility validation / 나누기 가능성 검증

Thread Safety / 스레드 안전성:

  • Thread-safe: No shared state / 스레드 안전: 공유 상태 없음

Performance / 성능:

  • Time complexity: O(1) 시간 복잡도: O(1)
  • Single modulo operation 단일 나머지 연산

Important Note / 중요 참고:

  • Float values are truncated, not rounded 부동 소수점 값은 반올림이 아닌 버림
  • 2.9 becomes 2 (even), not 3 (odd) 2.9는 3(홀수)이 아닌 2(짝수)가 됨
  • For precise integer checking, use integer types 정확한 정수 검사를 위해 정수 타입 사용

Example / 예제:

v := validation.New(4, "value")
v.Even()  // Passes / 성공

v := validation.New(3, "value")
v.Even()  // Fails / 실패

v := validation.New(0, "value")
v.Even()  // Passes (zero is even) / 성공 (0은 짝수)

v := validation.New(-2, "value")
v.Even()  // Passes / 성공

v := validation.New(2.9, "value")
v.Even()  // Passes (truncated to 2) / 성공 (2로 버림)

// Pair validation / 쌍 검증
v := validation.New(count, "pair_count")
v.Positive().Even()

func (*Validator) False

func (v *Validator) False() *Validator

False validates that the value is boolean false. Requires exact boolean false value for strict validation.

False는 값이 불리언 false인지 검증합니다. 엄격한 검증을 위해 정확한 불리언 false 값이 필요합니다.

Parameters / 매개변수:

  • None (operates on validator's value) 없음 (validator의 값에 대해 작동)

Returns / 반환:

  • *Validator: Returns self for method chaining 메서드 체이닝을 위해 자신을 반환

Behavior / 동작:

  • Requires boolean type 불리언 타입 필요
  • Must be exactly false 정확히 false여야 함
  • Fails on true or non-boolean true 또는 불리언이 아니면 실패
  • No falsy conversion falsy 변환 없음

Use Cases / 사용 사례:

  • Negative confirmation / 부정 확인
  • Opt-out validation / 선택 해제 검증
  • Disabled state check / 비활성화 상태 확인
  • Default false requirement / 기본 false 요구사항

Thread Safety / 스레드 안전성:

  • Thread-safe: No shared state / 스레드 안전: 공유 상태 없음

Performance / 성능:

  • Time complexity: O(1) 시간 복잡도: O(1)
  • Type assertion only 타입 단언만

This validator checks if the value is exactly boolean false. Useful for negative confirmation validation. 이 검증기는 값이 정확히 불리언 false인지 확인합니다. 부정 확인 검증에 유용합니다.

Example / 예시:

// Valid - false / 유효 - false
declined := false
v := validation.New(declined, "marketing")
v.False()  // Passes

// Invalid - true / 무효 - true
v = validation.New(true, "opt_out")
v.False()  // Fails

// Invalid - not boolean / 무효 - 불리언 아님
v = validation.New(0, "value")
v.False()  // Fails (not bool type)

Validation rules / 검증 규칙:

  • Value must be boolean type / 값이 불리언 타입이어야 함
  • Value must be false / 값이 false여야 함
Example

ExampleValidator_False demonstrates boolean false validation. ExampleValidator_False는 불리언 false 검증을 보여줍니다.

package main

import (
	"fmt"

	"github.com/arkd0ng/go-utils/validation"
)

func main() {
	// Validate newsletter opt-out (must be false)
	optIn := false
	v := validation.New(optIn, "newsletter_opt_in")
	v.False()

	err := v.Validate()
	if err != nil {
		fmt.Println("Must opt out of newsletter")
	} else {
		fmt.Println("Newsletter opt-out confirmed")
	}
}
Output:

Newsletter opt-out confirmed

func (*Validator) FileExists

func (v *Validator) FileExists() *Validator

FileExists validates that a file or directory exists at the given path. Performs filesystem existence check using os.Stat.

FileExists는 주어진 경로에 파일이나 디렉토리가 존재하는지 검증합니다. os.Stat을 사용하여 파일시스템 존재 여부를 확인합니다.

Parameters / 매개변수:

  • None (operates on validator's value as file path) 없음 (validator의 값을 파일 경로로 사용)

Returns / 반환:

  • *Validator: Returns self for method chaining 메서드 체이닝을 위해 자신을 반환

Behavior / 동작:

  • Uses os.Stat to check existence os.Stat을 사용하여 존재 확인
  • Accepts both files and directories 파일과 디렉토리 모두 허용
  • Follows symlinks (os.Stat behavior) 심볼릭 링크 추적 (os.Stat 동작)
  • Fails if path does not exist 경로가 존재하지 않으면 실패
  • Fails if value is not string 값이 문자열이 아니면 실패

Use Cases / 사용 사례:

  • Configuration file validation / 구성 파일 검증
  • Input file validation / 입력 파일 검증
  • Resource existence check / 리소스 존재 확인
  • Dependency validation / 의존성 검증

Thread Safety / 스레드 안전성:

  • Thread-safe: No shared state / 스레드 안전: 공유 상태 없음
  • Note: Filesystem state may change between check and use (TOCTOU) 참고: 확인과 사용 사이에 파일시스템 상태가 변경될 수 있음 (TOCTOU)

Performance / 성능:

  • Time complexity: O(1) filesystem operation 시간 복잡도: O(1) 파일시스템 작업
  • Performs actual filesystem I/O 실제 파일시스템 I/O 수행

Example / 예제:

// Existing file / 존재하는 파일
v := validation.New("/etc/hosts", "hosts_file")
v.FileExists()  // Passes if file exists

// Existing directory / 존재하는 디렉토리
v = validation.New("/usr/local", "local_dir")
v.FileExists()  // Passes (directories accepted)

// Non-existing file / 존재하지 않는 파일
v = validation.New("/nonexistent/file.txt", "missing_file")
v.FileExists()  // Fails

func (*Validator) FileExtension

func (v *Validator) FileExtension(extensions ...string) *Validator

FileExtension validates that a file has one of the specified extensions. Case-sensitive extension matching with automatic dot prefix handling.

FileExtension은 파일이 지정된 확장자 중 하나를 가지고 있는지 검증합니다. 자동 점 접두사 처리를 포함한 대소문자 구분 확장자 매칭입니다.

Parameters / 매개변수:

  • extensions: Allowed file extensions (with or without leading dot) 허용된 파일 확장자 (점 포함 또는 제외)

Returns / 반환:

  • *Validator: Returns self for method chaining 메서드 체이닝을 위해 자신을 반환

Behavior / 동작:

  • Uses filepath.Ext to extract extension filepath.Ext를 사용하여 확장자 추출
  • Automatically adds dot prefix if missing 점 접두사가 없으면 자동 추가
  • Case-sensitive matching (.txt != .TXT) 대소문자 구분 매칭 (.txt != .TXT)
  • Fails if file has no extension 파일에 확장자가 없으면 실패
  • Fails if extension not in allowed list 확장자가 허용 목록에 없으면 실패
  • Fails if value is not string 값이 문자열이 아니면 실패

Use Cases / 사용 사례:

  • Upload file type validation / 업로드 파일 유형 검증
  • Configuration file format check / 구성 파일 형식 확인
  • Input file type validation / 입력 파일 유형 검증
  • Security whitelisting / 보안 화이트리스트

Thread Safety / 스레드 안전성:

  • Thread-safe: No shared state / 스레드 안전: 공유 상태 없음

Performance / 성능:

  • Time complexity: O(n*m), n = extensions count, m = avg extension length 시간 복잡도: O(n*m), n = 확장자 개수, m = 평균 확장자 길이
  • No filesystem I/O 파일시스템 I/O 없음

Example / 예제:

// Image files / 이미지 파일
v := validation.New("/tmp/photo.jpg", "photo")
v.FileExtension("jpg", "jpeg", "png", "gif")  // Passes

// With or without dot / 점 포함 또는 제외
v = validation.New("/tmp/data.json", "data")
v.FileExtension(".json", ".xml")  // Passes (dot prefix)
v.FileExtension("json", "xml")    // Passes (auto-added dot)

// Case-sensitive / 대소문자 구분
v = validation.New("/tmp/file.TXT", "file")
v.FileExtension("txt")  // Fails (case mismatch)

// No extension / 확장자 없음
v = validation.New("/tmp/Makefile", "makefile")
v.FileExtension("txt", "md")  // Fails (no extension)

func (*Validator) FilePath

func (v *Validator) FilePath() *Validator

FilePath validates that the value is a valid file path format. Checks path format validity without verifying actual file existence.

FilePath는 값이 유효한 파일 경로 형식인지 검증합니다. 실제 파일 존재 여부를 확인하지 않고 경로 형식의 유효성만 확인합니다.

Parameters / 매개변수:

  • None (operates on validator's value) 없음 (validator의 값에 대해 작동)

Returns / 반환:

  • *Validator: Returns self for method chaining 메서드 체이닝을 위해 자신을 반환

Behavior / 동작:

  • Normalizes path using filepath.Clean filepath.Clean을 사용하여 경로 정규화
  • Accepts both absolute and relative paths 절대 경로와 상대 경로 모두 허용
  • Rejects empty paths and "." (current directory) 빈 경로와 "." (현재 디렉토리) 거부
  • Does not check file existence 파일 존재 여부 확인 안 함
  • Fails if value is not string 값이 문자열이 아니면 실패

Use Cases / 사용 사례:

  • File path format validation / 파일 경로 형식 검증
  • Configuration path validation / 구성 경로 검증
  • Input path validation / 입력 경로 검증
  • Path sanitization check / 경로 정제 확인

Thread Safety / 스레드 안전성:

  • Thread-safe: No shared state / 스레드 안전: 공유 상태 없음

Performance / 성능:

  • Time complexity: O(n), n = path length 시간 복잡도: O(n), n = 경로 길이
  • No filesystem I/O operations 파일시스템 I/O 작업 없음

Example / 예제:

// Valid file paths / 유효한 파일 경로
v := validation.New("/etc/config.yaml", "config_path")
v.FilePath()  // Passes (absolute path)

v = validation.New("./data/file.txt", "data_path")
v.FilePath()  // Passes (relative path)

// Invalid paths / 무효한 경로
v = validation.New("", "empty_path")
v.FilePath()  // Fails (empty string)

v = validation.New(".", "current_dir")
v.FilePath()  // Fails (current directory marker)

func (*Validator) FileReadable

func (v *Validator) FileReadable() *Validator

FileReadable validates that a file can be opened for reading. Attempts to open the file and verifies read permissions.

FileReadable은 파일을 읽기 위해 열 수 있는지 검증합니다. 파일을 열어보고 읽기 권한을 확인합니다.

Parameters / 매개변수:

  • None (operates on validator's value as file path) 없음 (validator의 값을 파일 경로로 사용)

Returns / 반환:

  • *Validator: Returns self for method chaining 메서드 체이닝을 위해 자신을 반환

Behavior / 동작:

  • Uses os.Open to verify read access os.Open을 사용하여 읽기 접근 확인
  • Closes file immediately after check 확인 후 즉시 파일 닫기
  • Checks both existence and permissions 존재와 권한 모두 확인
  • Fails if file cannot be opened 파일을 열 수 없으면 실패
  • Fails if value is not string 값이 문자열이 아니면 실패

Use Cases / 사용 사례:

  • Input file validation / 입력 파일 검증
  • Configuration file access check / 구성 파일 접근 확인
  • Data file validation / 데이터 파일 검증
  • Permission validation / 권한 검증

Thread Safety / 스레드 안전성:

  • Thread-safe: No shared state / 스레드 안전: 공유 상태 없음
  • Note: File permissions may change between check and actual use 참고: 확인과 실제 사용 사이에 파일 권한이 변경될 수 있음

Performance / 성능:

  • Time complexity: O(1) filesystem operation 시간 복잡도: O(1) 파일시스템 작업
  • Opens and closes file (I/O overhead) 파일 열기 및 닫기 (I/O 오버헤드)

Example / 예제:

// Readable file / 읽기 가능한 파일
v := validation.New("/etc/hosts", "hosts_file")
v.FileReadable()  // Passes if readable

// Permission denied / 권한 거부
v = validation.New("/root/secret.txt", "secret_file")
v.FileReadable()  // Fails if no read permission

// Directory (not readable as file) / 디렉토리 (파일로 읽을 수 없음)
v = validation.New("/usr", "usr_dir")
v.FileReadable()  // May pass (os.Open can open directories)

func (*Validator) FileSize

func (v *Validator) FileSize(min, max int64) *Validator

FileSize validates that a file's size is within the specified byte range (inclusive). Checks both file existence and size constraints.

FileSize는 파일 크기가 지정된 바이트 범위 내에 있는지 검증합니다 (포함). 파일 존재와 크기 제약을 모두 확인합니다.

Parameters / 매개변수:

  • min: Minimum file size in bytes (inclusive) 최소 파일 크기 (바이트, 포함)
  • max: Maximum file size in bytes (inclusive) 최대 파일 크기 (바이트, 포함)

Returns / 반환:

  • *Validator: Returns self for method chaining 메서드 체이닝을 위해 자신을 반환

Behavior / 동작:

  • Uses os.Stat to get file info os.Stat을 사용하여 파일 정보 가져오기
  • Accepts sizes within [min, max] range (inclusive) [min, max] 범위의 크기 허용 (포함)
  • Rejects directories (only files) 디렉토리 거부 (파일만 허용)
  • Fails if file does not exist 파일이 존재하지 않으면 실패
  • Fails if value is not string 값이 문자열이 아니면 실패

Use Cases / 사용 사례:

  • Upload file size validation / 업로드 파일 크기 검증
  • Configuration file size check / 구성 파일 크기 확인
  • Data file validation / 데이터 파일 검증
  • Resource quota enforcement / 리소스 할당량 적용

Thread Safety / 스레드 안전성:

  • Thread-safe: No shared state / 스레드 안전: 공유 상태 없음
  • Note: File size may change between check and use 참고: 확인과 사용 사이에 파일 크기가 변경될 수 있음

Performance / 성능:

  • Time complexity: O(1) filesystem operation 시간 복잡도: O(1) 파일시스템 작업
  • Single os.Stat call 단일 os.Stat 호출

Example / 예제:

// Size constraints (1 KB - 10 MB) / 크기 제약 (1 KB - 10 MB)
v := validation.New("/tmp/upload.pdf", "upload")
v.FileSize(1024, 10*1024*1024)  // 1 KB min, 10 MB max

// Empty file allowed / 빈 파일 허용
v = validation.New("/tmp/empty.txt", "empty_file")
v.FileSize(0, 100)  // 0 - 100 bytes

// Exact size / 정확한 크기
v = validation.New("/tmp/data.bin", "data")
v.FileSize(1024, 1024)  // Must be exactly 1 KB

func (*Validator) FileWritable

func (v *Validator) FileWritable() *Validator

FileWritable validates that a file is writable or its parent directory allows file creation. For existing files, checks write permissions. For new files, tests parent directory writability.

FileWritable은 파일이 쓰기 가능하거나 부모 디렉토리가 파일 생성을 허용하는지 검증합니다. 기존 파일의 경우 쓰기 권한을 확인합니다. 새 파일의 경우 부모 디렉토리의 쓰기 가능성을 테스트합니다.

Parameters / 매개변수:

  • None (operates on validator's value as file path) 없음 (validator의 값을 파일 경로로 사용)

Returns / 반환:

  • *Validator: Returns self for method chaining 메서드 체이닝을 위해 자신을 반환

Behavior / 동작:

  • For existing files: Opens with O_WRONLY|O_APPEND flags 기존 파일: O_WRONLY|O_APPEND 플래그로 열기
  • For new files: Tests parent directory by creating temp file 새 파일: 임시 파일을 생성하여 부모 디렉토리 테스트
  • Cleans up temporary test file immediately 임시 테스트 파일 즉시 정리
  • Fails if file/directory is not writable 파일/디렉토리가 쓰기 불가능하면 실패
  • Fails if value is not string 값이 문자열이 아니면 실패

Use Cases / 사용 사례:

  • Output file validation / 출력 파일 검증
  • Log file validation / 로그 파일 검증
  • Configuration file update check / 구성 파일 업데이트 확인
  • Data export validation / 데이터 내보내기 검증

Thread Safety / 스레드 안전성:

  • Thread-safe: No shared state / 스레드 안전: 공유 상태 없음
  • Note: Permissions may change between check and write 참고: 확인과 쓰기 사이에 권한이 변경될 수 있음

Performance / 성능:

  • Time complexity: O(1) filesystem operations 시간 복잡도: O(1) 파일시스템 작업
  • Creates and deletes temp file for new files (I/O overhead) 새 파일의 경우 임시 파일 생성 및 삭제 (I/O 오버헤드)

Example / 예제:

// Existing writable file / 기존 쓰기 가능한 파일
v := validation.New("/tmp/output.txt", "output_file")
v.FileWritable()  // Passes if writable

// New file in writable directory / 쓰기 가능한 디렉토리의 새 파일
v = validation.New("/tmp/newfile.log", "log_file")
v.FileWritable()  // Passes if /tmp is writable

// Read-only file / 읽기 전용 파일
v = validation.New("/etc/hosts", "hosts_file")
v.FileWritable()  // Fails (permission denied)

func (*Validator) FloatRange

func (v *Validator) FloatRange(min, max float64) *Validator

FloatRange validates that a floating-point value is within the specified range (inclusive). Accepts float32, float64, and all integer types with automatic conversion.

FloatRange는 부동소수점 값이 지정된 범위 내에 있는지 검증합니다 (포함). float32, float64 및 모든 정수 타입을 자동 변환과 함께 허용합니다.

Parameters / 매개변수:

  • min: Minimum value (inclusive) 최소값 (포함)
  • max: Maximum value (inclusive) 최대값 (포함)

Returns / 반환:

  • *Validator: Returns self for method chaining 메서드 체이닝을 위해 자신을 반환

Behavior / 동작:

  • Accepts float32 and float64 types float32 및 float64 타입 허용
  • Accepts all integer types (converted to float64) 모든 정수 타입 허용 (float64로 변환)
  • Inclusive range: min <= value <= max 포함 범위: min <= 값 <= max
  • Automatically converts to float64 for comparison 비교를 위해 float64로 자동 변환
  • Fails if value is not numeric 값이 숫자가 아니면 실패

Use Cases / 사용 사례:

  • Temperature range validation / 온도 범위 검증
  • Percentage validation / 백분율 검증
  • Price range validation / 가격 범위 검증
  • Measurement validation / 측정값 검증

Thread Safety / 스레드 안전성:

  • Thread-safe: No shared state / 스레드 안전: 공유 상태 없음

Performance / 성능:

  • Time complexity: O(1) 시간 복잡도: O(1)
  • Type switch + comparison 타입 스위치 + 비교

The range is inclusive: min <= value <= max

Example / 예제:

// Temperature validation / 온도 검증
v := validation.New(98.6, "temperature")
v.FloatRange(95.0, 105.0)  // Passes (normal body temp)

// Percentage validation / 백분율 검증
v = validation.New(85.5, "grade")
v.FloatRange(0.0, 100.0)  // Passes

// Boundaries included / 경계값 포함
v = validation.New(0.0, "value")
v.FloatRange(0.0, 10.0)  // Passes (min included)

v = validation.New(10.0, "value")
v.FloatRange(0.0, 10.0)  // Passes (max included)

// Integer accepted / 정수 허용
v = validation.New(98, "temp")
v.FloatRange(95.0, 105.0)  // Passes (converted to float)

// Out of range / 범위 밖
v = validation.New(110.5, "temperature")
v.FloatRange(95.0, 105.0)  // Fails

err := v.Validate()
Example

ExampleValidator_FloatRange demonstrates float range validation ExampleValidator_FloatRange는 실수 범위 검증을 보여줍니다

package main

import (
	"fmt"

	"github.com/arkd0ng/go-utils/validation"
)

func main() {
	v := validation.New(98.6, "temperature")
	v.FloatRange(95.0, 105.0)
	err := v.Validate()
	if err != nil {
		fmt.Println("Temperature is out of range")
	} else {
		fmt.Println("Valid temperature")
	}
}
Output:

Valid temperature

func (*Validator) GetErrors

func (v *Validator) GetErrors() []ValidationError

GetErrors returns all validation errors collected so far. It provides direct access to the error collection for custom processing.

GetErrors는 지금까지 수집된 모든 검증 에러를 반환합니다. 사용자 정의 처리를 위해 에러 컬렉션에 직접 액세스를 제공합니다.

Returns / 반환값:

  • []ValidationError: Slice of all validation errors (empty if no errors) 모든 검증 에러의 슬라이스 (에러가 없으면 빈 슬라이스)

Behavior / 동작:

  • Returns the actual error slice (not a copy) 실제 에러 슬라이스 반환 (복사본 아님)
  • Returns empty slice if no validation errors 검증 에러가 없으면 빈 슬라이스 반환
  • Does not clear the error collection 에러 컬렉션을 지우지 않음

Use Cases / 사용 사례:

  • Custom error formatting / 사용자 정의 에러 포맷팅
  • Conditional error handling / 조건부 에러 처리
  • Logging specific error details / 특정 에러 상세 정보 로깅
  • Filtering errors by field or rule / 필드 또는 규칙별 에러 필터링

Thread Safety / 스레드 안전성:

  • Thread-safe: Read-only operation 스레드 안전: 읽기 전용 작업
  • Warning: Modifying returned slice affects validator state 경고: 반환된 슬라이스 수정 시 검증기 상태 영향

Performance / 성능:

  • Time complexity: O(1) 시간 복잡도: O(1)
  • No memory allocation (returns existing slice) 메모리 할당 없음 (기존 슬라이스 반환)

Example / 예제:

v := validation.New(data, "data")
v.Required().Email().MinLength(5)

errors := v.GetErrors()
if len(errors) > 0 {
    for _, err := range errors {
        log.Printf("Validation error on %s: %s", err.Field, err.Message)
    }
}

// Check for specific field errors / 특정 필드 에러 확인
hasEmailError := false
for _, err := range v.GetErrors() {
    if err.Field == "email" {
        hasEmailError = true
        break
    }
}

func (*Validator) GreaterThan

func (v *Validator) GreaterThan(value float64) *Validator

GreaterThan validates that the numeric value is strictly greater than the given value. Works with all numeric types: int, int8-64, uint, uint8-64, float32, float64.

GreaterThan은 숫자 값이 주어진 값보다 엄격하게 큰지 검증합니다. 모든 숫자 타입에서 작동합니다: int, int8-64, uint, uint8-64, float32, float64.

Parameters / 매개변수:

  • value: The threshold value (exclusive) 임계값 (미포함)

Returns / 반환:

  • *Validator: Returns self for method chaining 메서드 체이닝을 위해 자신을 반환

Behavior / 동작:

  • Accepts value if val > threshold val > 임계값이면 허용
  • Exclusive comparison (equals fails) 미포함 비교 (같으면 실패)
  • Converts to float64 for comparison 비교를 위해 float64로 변환
  • Fails if value is not numeric 값이 숫자가 아니면 실패

Use Cases / 사용 사례:

  • Minimum threshold validation / 최소 임계값 검증
  • Score requirements / 점수 요구사항
  • Range validation (with LessThan) 범위 검증 (LessThan과 함께)
  • Positive number validation / 양수 검증

Thread Safety / 스레드 안전성:

  • Thread-safe: No shared state / 스레드 안전: 공유 상태 없음

Performance / 성능:

  • Time complexity: O(1) 시간 복잡도: O(1)
  • Simple numeric comparison 단순 숫자 비교

Comparison with Min() / Min()과의 비교:

  • GreaterThan(5): value must be > 5 (6, 7, 8...)
  • Min(5): value must be >= 5 (5, 6, 7...)
  • Use GreaterThan for exclusive bounds 미포함 경계에는 GreaterThan 사용

Example / 예제:

// Exclusive threshold / 미포함 임계값
v := validation.New(10, "score")
v.GreaterThan(5)  // Passes (10 > 5) / 성공

v := validation.New(5, "score")
v.GreaterThan(5)  // Fails (5 = 5, not >) / 실패

// Positive validation / 양수 검증
v := validation.New(amount, "amount")
v.GreaterThan(0)  // Must be positive

// Range validation / 범위 검증
v := validation.New(value, "value")
v.GreaterThan(0).LessThan(100)  // 0 < value < 100

func (*Validator) GreaterThanOrEqual

func (v *Validator) GreaterThanOrEqual(value float64) *Validator

GreaterThanOrEqual validates that the numeric value is greater than or equal to the given value. Works with all numeric types: int, int8-64, uint, uint8-64, float32, float64.

GreaterThanOrEqual은 숫자 값이 주어진 값보다 크거나 같은지 검증합니다. 모든 숫자 타입에서 작동합니다: int, int8-64, uint, uint8-64, float32, float64.

Parameters / 매개변수:

  • value: The minimum threshold value (inclusive) 최소 임계값 (포함)

Returns / 반환:

  • *Validator: Returns self for method chaining 메서드 체이닝을 위해 자신을 반환

Behavior / 동작:

  • Accepts value if val >= threshold val >= 임계값이면 허용
  • Inclusive comparison (equals passes) 포함 비교 (같으면 통과)
  • Converts to float64 for comparison 비교를 위해 float64로 변환
  • Fails if value is not numeric 값이 숫자가 아니면 실패

Use Cases / 사용 사례:

  • Minimum value validation / 최소값 검증
  • Non-negative validation / 음수가 아닌 값 검증
  • Threshold requirements / 임계값 요구사항
  • Quota validation / 할당량 검증

Thread Safety / 스레드 안전성:

  • Thread-safe: No shared state / 스레드 안전: 공유 상태 없음

Performance / 성능:

  • Time complexity: O(1) 시간 복잡도: O(1)
  • Simple numeric comparison 단순 숫자 비교

Comparison with Min() / Min()과의 비교:

  • GreaterThanOrEqual(5): Same as Min(5)
  • Both accept value >= 5
  • Min() is more idiomatic for minimum bounds 최소 경계에는 Min()이 더 관용적

Example / 예제:

// Inclusive minimum / 포함 최소값
v := validation.New(10, "score")
v.GreaterThanOrEqual(10)  // Passes (10 >= 10) / 성공

v := validation.New(9, "score")
v.GreaterThanOrEqual(10)  // Fails (9 < 10) / 실패

// Non-negative validation / 음수가 아닌 값 검증
v := validation.New(count, "count")
v.GreaterThanOrEqual(0)  // Can be 0 or positive

// Minimum age / 최소 나이
v := validation.New(age, "age")
v.GreaterThanOrEqual(18)  // 18 or older

func (*Validator) HSL

func (v *Validator) HSL() *Validator

HSL validates that the value is a valid HSL color format. Format: hsl(h, s%, l%) where h is 0-360 degrees, s and l are 0-100%.

HSL은 값이 유효한 HSL 색상 형식인지 검증합니다. 형식: hsl(h, s%, l%) 여기서 h는 0-360도, s와 l은 0-100% 범위입니다.

Parameters / 매개변수:

  • None (operates on validator's value) 없음 (validator의 값에 대해 작동)

Returns / 반환:

  • *Validator: Returns self for method chaining 메서드 체이닝을 위해 자신을 반환

Behavior / 동작:

  • Validates hsl(h, s%, l%) format hsl(h, s%, l%) 형식 검증
  • Hue: 0-360 degrees (color wheel position) 색조: 0-360도 (색상환 위치)
  • Saturation: 0-100% (color intensity) 채도: 0-100% (색상 강도)
  • Lightness: 0-100% (brightness) 명도: 0-100% (밝기)
  • % symbol required for s and l s와 l에 % 기호 필수
  • Fails if value is not string 값이 문자열이 아니면 실패

Use Cases / 사용 사례:

  • CSS hsl() color validation / CSS hsl() 색상 검증
  • Design systems / 디자인 시스템
  • Color harmony calculations / 색상 조화 계산
  • Theme generation / 테마 생성

Thread Safety / 스레드 안전성:

  • Thread-safe: No shared state / 스레드 안전: 공유 상태 없음

Performance / 성능:

  • Time complexity: O(n), n = string length 시간 복잡도: O(n), n = 문자열 길이
  • Single regex match + 3 range checks 단일 정규식 매칭 + 3번의 범위 확인

Format: hsl(h, s%, l%) where h is 0-360, s and l are 0-100%. 형식: hsl(h, s%, l%) 여기서 h는 0-360, s와 l은 0-100% 범위입니다.

Example / 예시:

// Valid HSL colors / 유효한 HSL 색상
color := "hsl(9, 100%, 60%)"
v := validation.New(color, "theme_color")
v.HSL()  // Passes (orange-red)

// Red / 빨강
v = validation.New("hsl(0, 100%, 50%)", "color")
v.HSL()  // Passes

// Green / 초록
v = validation.New("hsl(120, 100%, 50%)", "color")
v.HSL()  // Passes

// Blue / 파랑
v = validation.New("hsl(240, 100%, 50%)", "color")
v.HSL()  // Passes

// Gray (no saturation) / 회색 (채도 없음)
v = validation.New("hsl(0, 0%, 50%)", "color")
v.HSL()  // Passes

// White / 흰색
v = validation.New("hsl(0, 0%, 100%)", "color")
v.HSL()  // Passes

// Black / 검정
v = validation.New("hsl(0, 0%, 0%)", "color")
v.HSL()  // Passes

// Invalid values / 무효한 값
v = validation.New("hsl(361, 100%, 50%)", "color")
v.HSL()  // Fails (hue > 360)

v = validation.New("hsl(0, 101%, 50%)", "color")
v.HSL()  // Fails (saturation > 100)

v = validation.New("hsl(0, 100, 50)", "color")
v.HSL()  // Fails (missing % symbols)

Validation rules / 검증 규칙:

  • Must be a string / 문자열이어야 함
  • Format: hsl(h, s%, l%) / 형식: hsl(h, s%, l%)
  • Hue must be 0-360 degrees / 색조는 0-360도 범위
  • Saturation and Lightness must be 0-100% / 채도와 명도는 0-100% 범위
Example

ExampleValidator_HSL demonstrates HSL color validation ExampleValidator_HSL는 HSL 색상 검증을 보여줍니다

package main

import (
	"fmt"

	"github.com/arkd0ng/go-utils/validation"
)

func main() {
	color := "hsl(9, 100%, 60%)"
	v := validation.New(color, "theme_color")
	v.HSL()

	if len(v.GetErrors()) > 0 {
		fmt.Println("Invalid HSL color")
	} else {
		fmt.Println("Valid HSL color")
	}
}
Output:

Valid HSL color

func (*Validator) Hex

func (v *Validator) Hex() *Validator

Hex validates that the value is a valid hexadecimal string. Supports optional '0x' or '0X' prefix and case-insensitive hex digits.

Hex는 값이 유효한 16진수 문자열인지 검증합니다. 선택적 '0x' 또는 '0X' 접두사와 대소문자 구분 없는 16진수를 지원합니다.

Parameters / 매개변수:

  • None (operates on validator's value) 없음 (validator의 값에 대해 작동)

Returns / 반환:

  • *Validator: Returns self for method chaining 메서드 체이닝을 위해 자신을 반환

Behavior / 동작:

  • Removes optional '0x' or '0X' prefix 선택적 '0x' 또는 '0X' 접두사 제거
  • Uses hex.DecodeString for validation hex.DecodeString을 사용하여 검증
  • Validates hex digits (0-9, A-F, a-f) 16진수 검증 (0-9, A-F, a-f)
  • Requires even number of characters 짝수 개의 문자 필요
  • Case-insensitive 대소문자 구분 없음
  • Fails if value is not string 값이 문자열이 아니면 실패

Use Cases / 사용 사례:

  • Hex encoded data validation / 16진수 인코딩 데이터 검증
  • Binary data representation / 바이너리 데이터 표현
  • Cryptographic hash validation / 암호화 해시 검증
  • Memory address validation / 메모리 주소 검증

Thread Safety / 스레드 안전성:

  • Thread-safe: No shared state / 스레드 안전: 공유 상태 없음

Performance / 성능:

  • Time complexity: O(n), n = string length 시간 복잡도: O(n), n = 문자열 길이
  • Single hex.DecodeString call 단일 hex.DecodeString 호출

Example / 예제:

// Valid hex strings / 유효한 16진수 문자열
v := validation.New("48656c6c6f", "hex_data")
v.Hex()  // Passes (even length)

// With 0x prefix / 0x 접두사 포함
v = validation.New("0x48656c6c6f", "hex")
v.Hex()  // Passes (prefix removed)

// Uppercase / 대문자
v = validation.New("ABCDEF123456", "hex")
v.Hex()  // Passes

// Mixed case / 대소문자 혼합
v = validation.New("AbCdEf123456", "hex")
v.Hex()  // Passes

// With 0X prefix / 0X 접두사 포함
v = validation.New("0XABCDEF", "hex")
v.Hex()  // Passes

// Invalid - odd length / 무효 - 홀수 길이
v = validation.New("ABC", "hex")
v.Hex()  // Fails (must be even length)

// Invalid - non-hex character / 무효 - 16진수가 아닌 문자
v = validation.New("GHIJKL", "hex")
v.Hex()  // Fails (G-L not hex)

func (*Validator) HexColor

func (v *Validator) HexColor() *Validator

HexColor validates that the value is a valid hexadecimal color code. Supports 3-digit (#RGB) and 6-digit (#RRGGBB) formats, with optional # prefix.

HexColor는 값이 유효한 16진수 색상 코드인지 검증합니다. 3자리(#RGB) 및 6자리(#RRGGBB) 형식을 지원하며, # 접두사는 선택 사항입니다.

Parameters / 매개변수:

  • None (operates on validator's value) 없음 (validator의 값에 대해 작동)

Returns / 반환:

  • *Validator: Returns self for method chaining 메서드 체이닝을 위해 자신을 반환

Behavior / 동작:

  • Accepts 3-digit hex (#RGB or RGB) 3자리 16진수 허용 (#RGB 또는 RGB)
  • Accepts 6-digit hex (#RRGGBB or RRGGBB) 6자리 16진수 허용 (#RRGGBB 또는 RRGGBB)
  • # prefix is optional # 접두사 선택 사항
  • Case-insensitive (A-F or a-f) 대소문자 구분 없음 (A-F 또는 a-f)
  • Fails if value is not string 값이 문자열이 아니면 실패

Use Cases / 사용 사례:

  • Web color validation / 웹 색상 검증
  • CSS color input / CSS 색상 입력
  • Design system colors / 디자인 시스템 색상
  • Brand color validation / 브랜드 색상 검증

Thread Safety / 스레드 안전성:

  • Thread-safe: No shared state / 스레드 안전: 공유 상태 없음

Performance / 성능:

  • Time complexity: O(n), n = string length 시간 복잡도: O(n), n = 문자열 길이
  • Single regex match 단일 정규식 매칭

Supports both 3-digit (#RGB) and 6-digit (#RRGGBB) hex colors, with or without # prefix. 3자리(#RGB) 및 6자리(#RRGGBB) 16진수 색상을 모두 지원하며, # 접두사는 선택 사항입니다.

Example / 예시:

// 6-digit with # / # 포함 6자리
color := "#FF5733"
v := validation.New(color, "brand_color")
v.HexColor()  // Passes

// 6-digit without # / # 없는 6자리
v = validation.New("FF5733", "color")
v.HexColor()  // Passes

// 3-digit shorthand / 3자리 축약형
v = validation.New("#F53", "color")
v.HexColor()  // Passes (equivalent to #FF5533)

// Case-insensitive / 대소문자 구분 없음
v = validation.New("#ff5733", "color")
v.HexColor()  // Passes

// Invalid formats / 무효한 형식
v = validation.New("#GG5733", "color")
v.HexColor()  // Fails (invalid hex)

v = validation.New("#F5", "color")
v.HexColor()  // Fails (2 digits, not 3 or 6)

Validation rules / 검증 규칙:

  • Must be a string / 문자열이어야 함
  • Format: #RGB or #RRGGBB (# is optional) / 형식: #RGB 또는 #RRGGBB (# 선택)
  • RGB values must be hexadecimal (0-9, A-F) / RGB 값은 16진수여야 함
Example

ExampleValidator_HexColor demonstrates hex color validation ExampleValidator_HexColor는 16진수 색상 검증을 보여줍니다

package main

import (
	"fmt"

	"github.com/arkd0ng/go-utils/validation"
)

func main() {
	color := "#FF5733"
	v := validation.New(color, "brand_color")
	v.HexColor()

	if len(v.GetErrors()) > 0 {
		fmt.Println("Invalid hex color")
	} else {
		fmt.Println("Valid hex color")
	}
}
Output:

Valid hex color

func (*Validator) IP

func (v *Validator) IP() *Validator

IP validates that the value is a valid IP address (IPv4 or IPv6). Accepts both IPv4 and IPv6 formats. Use IPv4() or IPv6() for version-specific validation.

IP는 값이 유효한 IP 주소(IPv4 또는 IPv6)인지 검증합니다. IPv4 및 IPv6 형식 모두 허용합니다. 버전별 검증은 IPv4() 또는 IPv6()를 사용하세요.

Parameters / 매개변수:

  • None (operates on validator's value) 없음 (validator의 값에 대해 작동)

Returns / 반환:

  • *Validator: Returns self for method chaining 메서드 체이닝을 위해 자신을 반환

Behavior / 동작:

  • Uses net.ParseIP for format validation 형식 검증을 위해 net.ParseIP 사용
  • Accepts both IPv4 and IPv6 addresses IPv4 및 IPv6 주소 모두 허용
  • Validates format without version restriction 버전 제한 없이 형식 검증
  • Fails if value is not string 값이 문자열이 아니면 실패

Use Cases / 사용 사례:

  • Version-agnostic IP validation / 버전 무관 IP 검증
  • Dual-stack environments / 듀얼 스택 환경
  • Generic IP configuration / 일반 IP 구성
  • Protocol-independent validation / 프로토콜 독립적 검증

Thread Safety / 스레드 안전성:

  • Thread-safe: No shared state / 스레드 안전: 공유 상태 없음

Performance / 성능:

  • Time complexity: O(n), n = string length 시간 복잡도: O(n), n = 문자열 길이
  • Single net.ParseIP call 단일 net.ParseIP 호출

This validator accepts both IPv4 and IPv6 addresses. Use IPv4() or IPv6() for specific version validation.

Example / 예제:

// IPv4 addresses / IPv4 주소
v := validation.New("192.168.1.1", "ip_address")
v.IP()  // Passes

v = validation.New("10.0.0.1", "server_ip")
v.IP()  // Passes

// IPv6 addresses / IPv6 주소
v = validation.New("2001:db8::1", "ip_address")
v.IP()  // Passes

v = validation.New("::1", "loopback")
v.IP()  // Passes

// Invalid addresses / 무효한 주소
v = validation.New("999.999.999.999", "ip")
v.IP()  // Fails

v = validation.New("not-an-ip", "ip")
v.IP()  // Fails
Example

ExampleValidator_IP demonstrates the IP validator ExampleValidator_IP는 IP 검증기를 보여줍니다

package main

import (
	"fmt"

	"github.com/arkd0ng/go-utils/validation"
)

func main() {
	v := validation.New("10.0.0.1", "ip_address")
	v.IP()
	err := v.Validate()
	if err != nil {
		fmt.Println("Invalid IP address")
	} else {
		fmt.Println("Valid IP address")
	}
}
Output:

Valid IP address

func (*Validator) IPv4

func (v *Validator) IPv4() *Validator

IPv4 validates that the value is a valid IPv4 address. Uses net.ParseIP with IPv4-specific validation.

IPv4는 값이 유효한 IPv4 주소인지 검증합니다. IPv4 전용 검증과 함께 net.ParseIP를 사용합니다.

Parameters / 매개변수:

  • None (operates on validator's value) 없음 (validator의 값에 대해 작동)

Returns / 반환:

  • *Validator: Returns self for method chaining 메서드 체이닝을 위해 자신을 반환

Behavior / 동작:

  • Uses net.ParseIP for format validation 형식 검증을 위해 net.ParseIP 사용
  • Validates IPv4 format (xxx.xxx.xxx.xxx) IPv4 형식 검증 (xxx.xxx.xxx.xxx)
  • Each octet must be 0-255 각 옥텟은 0-255 범위
  • No leading zeros except for 0 itself 0 자체를 제외한 선행 0 없음
  • Rejects IPv6 addresses IPv6 주소 거부
  • Fails if value is not string 값이 문자열이 아니면 실패

Use Cases / 사용 사례:

  • Server IP validation / 서버 IP 검증
  • Network configuration / 네트워크 구성
  • Firewall rules / 방화벽 규칙
  • IPv4-only environments / IPv4 전용 환경

Thread Safety / 스레드 안전성:

  • Thread-safe: No shared state / 스레드 안전: 공유 상태 없음

Performance / 성능:

  • Time complexity: O(n), n = string length 시간 복잡도: O(n), n = 문자열 길이
  • Single net.ParseIP call 단일 net.ParseIP 호출

The validator checks for / 검증기 확인 사항: - Valid IPv4 format (xxx.xxx.xxx.xxx) - Each octet in range 0-255 - No leading zeros (except for 0 itself)

Example / 예제:

// Valid IPv4 addresses / 유효한 IPv4 주소
v := validation.New("192.168.1.1", "ip_address")
v.IPv4()  // Passes

v = validation.New("10.0.0.1", "server_ip")
v.IPv4()  // Passes

v = validation.New("255.255.255.255", "broadcast")
v.IPv4()  // Passes

// Invalid addresses / 무효한 주소
v = validation.New("256.1.1.1", "ip")
v.IPv4()  // Fails (octet > 255)

v = validation.New("2001:db8::1", "ip")
v.IPv4()  // Fails (IPv6 address)
Example

ExampleValidator_IPv4 demonstrates the IPv4 validator ExampleValidator_IPv4는 IPv4 검증기를 보여줍니다

package main

import (
	"fmt"

	"github.com/arkd0ng/go-utils/validation"
)

func main() {
	v := validation.New("192.168.1.1", "ip_address")
	v.IPv4()
	err := v.Validate()
	if err != nil {
		fmt.Println("Invalid IPv4 address")
	} else {
		fmt.Println("Valid IPv4 address")
	}
}
Output:

Valid IPv4 address

func (*Validator) IPv6

func (v *Validator) IPv6() *Validator

IPv6 validates that the value is a valid IPv6 address. Uses net.ParseIP with IPv6-specific validation.

IPv6는 값이 유효한 IPv6 주소인지 검증합니다. IPv6 전용 검증과 함께 net.ParseIP를 사용합니다.

Parameters / 매개변수:

  • None (operates on validator's value) 없음 (validator의 값에 대해 작동)

Returns / 반환:

  • *Validator: Returns self for method chaining 메서드 체이닝을 위해 자신을 반환

Behavior / 동작:

  • Uses net.ParseIP for format validation 형식 검증을 위해 net.ParseIP 사용
  • Supports full IPv6 format (8 groups of 4 hex digits) 전체 IPv6 형식 지원 (4자리 16진수 8그룹)
  • Supports compressed notation (::) 압축 표기법 지원 (::)
  • Supports mixed notation (IPv4-mapped IPv6) 혼합 표기법 지원 (IPv4 매핑 IPv6)
  • Rejects IPv4 addresses IPv4 주소 거부
  • Fails if value is not string 값이 문자열이 아니면 실패

Use Cases / 사용 사례:

  • Modern network configuration / 최신 네트워크 구성
  • IPv6-only environments / IPv6 전용 환경
  • Dual-stack validation / 듀얼 스택 검증
  • Future-proof addressing / 미래 대비 주소 지정

Thread Safety / 스레드 안전성:

  • Thread-safe: No shared state / 스레드 안전: 공유 상태 없음

Performance / 성능:

  • Time complexity: O(n), n = string length 시간 복잡도: O(n), n = 문자열 길이
  • Single net.ParseIP call 단일 net.ParseIP 호출

The validator supports / 검증기 지원: - Full IPv6 format (8 groups of 4 hex digits) - Compressed notation (::) - Mixed notation (IPv4-mapped IPv6)

Example / 예제:

// Full IPv6 format / 전체 IPv6 형식
v := validation.New("2001:0db8:85a3:0000:0000:8a2e:0370:7334", "ip")
v.IPv6()  // Passes

// Compressed notation / 압축 표기법
v = validation.New("2001:db8:85a3::8a2e:370:7334", "ip")
v.IPv6()  // Passes

v = validation.New("::1", "loopback")
v.IPv6()  // Passes (IPv6 loopback)

// IPv4-mapped IPv6 / IPv4 매핑 IPv6
v = validation.New("::ffff:192.0.2.1", "ip")
v.IPv6()  // Passes

// Invalid addresses / 무효한 주소
v = validation.New("192.168.1.1", "ip")
v.IPv6()  // Fails (IPv4 address)
Example

ExampleValidator_IPv6 demonstrates the IPv6 validator ExampleValidator_IPv6는 IPv6 검증기를 보여줍니다

package main

import (
	"fmt"

	"github.com/arkd0ng/go-utils/validation"
)

func main() {
	v := validation.New("2001:db8::1", "ip_address")
	v.IPv6()
	err := v.Validate()
	if err != nil {
		fmt.Println("Invalid IPv6 address")
	} else {
		fmt.Println("Valid IPv6 address")
	}
}
Output:

Valid IPv6 address

func (*Validator) ISBN

func (v *Validator) ISBN() *Validator

ISBN validates International Standard Book Number (ISBN-10 or ISBN-13). Validates both formats with checksum verification.

ISBN는 국제 표준 도서 번호(ISBN-10 또는 ISBN-13)를 검증합니다. 체크섬 확인과 함께 두 형식을 모두 검증합니다.

Parameters / 매개변수:

  • None (operates on validator's value) 없음 (validator의 값에 대해 작동)

Returns / 반환:

  • *Validator: Returns self for method chaining 메서드 체이닝을 위해 자신을 반환

Behavior / 동작:

  • Accepts ISBN-10 (10 digits) ISBN-10 허용 (10자리)
  • Accepts ISBN-13 (13 digits) ISBN-13 허용 (13자리)
  • Allows hyphens and spaces (removed for validation) 하이픈 및 공백 허용 (검증 시 제거)
  • Validates checksum for both formats 두 형식 모두 체크섬 검증

Use Cases / 사용 사례:

  • Book cataloging systems / 도서 목록 시스템
  • E-commerce book stores / 전자상거래 서점
  • Library management / 도서관 관리
  • Publishing platforms / 출판 플랫폼

Thread Safety / 스레드 안전성:

  • Thread-safe: No shared state / 스레드 안전: 공유 상태 없음

Performance / 성능:

  • Time complexity: O(n), n = 10 or 13 시간 복잡도: O(n), n = 10 또는 13
  • Checksum calculation required 체크섬 계산 필요

Supports both ISBN-10 and ISBN-13 formats with or without hyphens. ISBN-10과 ISBN-13 형식을 모두 지원하며 하이픈 포함/미포함 가능합니다.

Example / 예시:

// Valid ISBN-13 / 유효한 ISBN-13
v := validation.New("978-0-596-52068-7", "isbn")
v.ISBN()  // Passes

// Valid ISBN-10 / 유효한 ISBN-10
v = validation.New("0-596-52068-9", "isbn")
v.ISBN()  // Passes

// Without hyphens / 하이픈 없이
v = validation.New("9780596520687", "isbn")
v.ISBN()  // Passes

// Invalid checksum / 무효한 체크섬
v = validation.New("978-0-596-52068-0", "isbn")
v.ISBN()  // Fails

Validation rules / 검증 규칙:

  • Must be a string / 문자열이어야 함
  • Must be 10 or 13 digits (excluding hyphens/spaces) / 10 또는 13자리 (하이픈/공백 제외)
  • Must pass checksum validation / 체크섬 검증 통과
Example

ExampleValidator_ISBN demonstrates ISBN validation ExampleValidator_ISBN는 ISBN 검증을 보여줍니다

package main

import (
	"fmt"

	"github.com/arkd0ng/go-utils/validation"
)

func main() {
	v := validation.New("978-0-596-52068-7", "isbn")
	v.ISBN()

	if len(v.GetErrors()) > 0 {
		fmt.Println("Invalid ISBN")
	} else {
		fmt.Println("Valid ISBN")
	}
}
Output:

Valid ISBN

func (*Validator) ISSN

func (v *Validator) ISSN() *Validator

ISSN validates International Standard Serial Number (ISSN-8). Validates 8-digit format with checksum verification.

ISSN는 국제 표준 연속 간행물 번호(ISSN-8)를 검증합니다. 체크섬 확인과 함께 8자리 형식을 검증합니다.

Parameters / 매개변수:

  • None (operates on validator's value) 없음 (validator의 값에 대해 작동)

Returns / 반환:

  • *Validator: Returns self for method chaining 메서드 체이닝을 위해 자신을 반환

Behavior / 동작:

  • Validates 8-digit format (7 digits + checksum) 8자리 형식 검증 (7자리 + 체크섬)
  • Checksum can be 0-9 or X 체크섬은 0-9 또는 X
  • Allows optional hyphen after 4th digit 4번째 자리 뒤 선택적 하이픈 허용
  • Validates checksum algorithm 체크섬 알고리즘 검증

Use Cases / 사용 사례:

  • Journal cataloging / 저널 목록 작성
  • Magazine subscription systems / 잡지 구독 시스템
  • Periodical databases / 정기 간행물 데이터베이스
  • Library serial management / 도서관 연속 간행물 관리

Thread Safety / 스레드 안전성:

  • Thread-safe: No shared state / 스레드 안전: 공유 상태 없음

Performance / 성능:

  • Time complexity: O(1), fixed length 시간 복잡도: O(1), 고정 길이
  • Checksum calculation: 7 operations 체크섬 계산: 7회 연산

ISSN format: XXXX-XXXX (8 digits with optional hyphen after 4th digit) ISSN 형식: XXXX-XXXX (4번째 자리 뒤에 선택적 하이픈이 있는 8자리)

Example / 예시:

// Valid with hyphen / 하이픈 포함 유효
v := validation.New("2049-3630", "issn")
v.ISSN()  // Passes

// Valid without hyphen / 하이픈 없이 유효
v = validation.New("20493630", "issn")
v.ISSN()  // Passes

// With X checksum / X 체크섬 포함
v = validation.New("0378-595X", "issn")
v.ISSN()  // Passes

// Invalid checksum / 무효한 체크섬
v = validation.New("2049-3631", "issn")
v.ISSN()  // Fails

Validation rules / 검증 규칙:

  • Must be a string / 문자열이어야 함
  • Must be 8 digits (excluding hyphen) / 8자리 (하이픈 제외)
  • Last digit can be 0-9 or X / 마지막 자리는 0-9 또는 X
  • Must pass checksum validation / 체크섬 검증 통과
Example

ExampleValidator_ISSN demonstrates ISSN validation ExampleValidator_ISSN는 ISSN 검증을 보여줍니다

package main

import (
	"fmt"

	"github.com/arkd0ng/go-utils/validation"
)

func main() {
	v := validation.New("2049-3630", "issn")
	v.ISSN()

	if len(v.GetErrors()) > 0 {
		fmt.Println("Invalid ISSN")
	} else {
		fmt.Println("Valid ISSN")
	}
}
Output:

Valid ISSN

func (*Validator) In

func (v *Validator) In(values ...interface{}) *Validator

In validates that the value exists in the given list of allowed values. Uses deep equality for comparison, supporting any comparable type.

In은 값이 주어진 허용 값 목록에 존재하는지 검증합니다. 깊은 동등성 비교를 사용하며 비교 가능한 모든 타입을 지원합니다.

Parameters / 매개변수:

  • values: Variadic list of allowed values 허용되는 값들의 가변 인자 목록

Returns / 반환:

  • *Validator: Returns self for method chaining 메서드 체이닝을 위해 자신을 반환

Behavior / 동작:

  • Uses reflect.DeepEqual for comparison reflect.DeepEqual을 사용하여 비교
  • Supports any type (strings, numbers, structs, etc.) 모든 타입 지원 (문자열, 숫자, 구조체 등)
  • Case-sensitive for strings 문자열은 대소문자 구분
  • Fails if value not found in list 목록에서 값을 찾지 못하면 실패

Use Cases / 사용 사례:

  • Enum-like validation / 열거형 유사 검증
  • Whitelist validation / 화이트리스트 검증
  • Status/state validation / 상태/상태 검증
  • Role-based validation / 역할 기반 검증
  • Allowed option selection / 허용된 옵션 선택

Thread Safety / 스레드 안전성:

  • Thread-safe: No shared state / 스레드 안전: 공유 상태 없음

Performance / 성능:

  • Time complexity: O(n) where n is number of allowed values 시간 복잡도: O(n) (n은 허용 값의 수)
  • Linear search through values list 값 목록을 선형 검색
  • DeepEqual can be expensive for complex types DeepEqual은 복잡한 타입에서 비용이 클 수 있음

Example / 예제:

// String values / 문자열 값
v := validation.New("red", "color")
v.In("red", "green", "blue")  // Passes / 성공

v := validation.New("yellow", "color")
v.In("red", "green", "blue")  // Fails / 실패

// Numeric values / 숫자 값
v := validation.New(2, "status")
v.In(1, 2, 3)  // Passes / 성공

// Status validation / 상태 검증
v := validation.New(status, "order_status")
v.Required().In("pending", "processing", "completed", "cancelled")

// Role validation / 역할 검증
v := validation.New(role, "user_role")
v.In("admin", "editor", "viewer")
Example

ExampleValidator_In demonstrates the In validator ExampleValidator_In는 In 검증기를 보여줍니다

package main

import (
	"fmt"

	"github.com/arkd0ng/go-utils/validation"
)

func main() {
	v := validation.New("apple", "fruit")
	v.In("apple", "banana", "orange")
	err := v.Validate()
	if err != nil {
		fmt.Println("Invalid fruit")
	} else {
		fmt.Println("Valid fruit")
	}
}
Output:

Valid fruit

func (*Validator) IntRange

func (v *Validator) IntRange(min, max int) *Validator

IntRange validates that an integer value is within the specified range (inclusive). Accepts all integer types (int, int8-64, uint, uint8-64) with automatic conversion.

IntRange는 정수 값이 지정된 범위 내에 있는지 검증합니다 (포함). 자동 변환을 통해 모든 정수 타입(int, int8-64, uint, uint8-64)을 허용합니다.

Parameters / 매개변수:

  • min: Minimum value (inclusive) 최소값 (포함)
  • max: Maximum value (inclusive) 최대값 (포함)

Returns / 반환:

  • *Validator: Returns self for method chaining 메서드 체이닝을 위해 자신을 반환

Behavior / 동작:

  • Accepts all signed integer types (int, int8, int16, int32, int64) 모든 부호 있는 정수 타입 허용 (int, int8, int16, int32, int64)
  • Accepts all unsigned integer types (uint, uint8, uint16, uint32, uint64) 모든 부호 없는 정수 타입 허용 (uint, uint8, uint16, uint32, uint64)
  • Inclusive range: min <= value <= max 포함 범위: min <= 값 <= max
  • Automatically converts to int64 for comparison 비교를 위해 int64로 자동 변환
  • Fails if value is not an integer type 값이 정수 타입이 아니면 실패

Use Cases / 사용 사례:

  • Age range validation / 나이 범위 검증
  • Quantity limits / 수량 제한
  • Score validation / 점수 검증
  • Rating systems / 평점 시스템

Thread Safety / 스레드 안전성:

  • Thread-safe: No shared state / 스레드 안전: 공유 상태 없음

Performance / 성능:

  • Time complexity: O(1) 시간 복잡도: O(1)
  • Type switch + comparison 타입 스위치 + 비교

The range is inclusive: min <= value <= max

Example / 예제:

// Age validation / 나이 검증
v := validation.New(25, "age")
v.IntRange(18, 65)  // Passes (working age)

// Score validation / 점수 검증
v = validation.New(85, "score")
v.IntRange(0, 100)  // Passes

// Boundaries included / 경계값 포함
v = validation.New(18, "age")
v.IntRange(18, 65)  // Passes (min included)

v = validation.New(65, "age")
v.IntRange(18, 65)  // Passes (max included)

// Out of range / 범위 밖
v = validation.New(150, "age")
v.IntRange(0, 120)  // Fails

err := v.Validate()
Example

ExampleValidator_IntRange demonstrates integer range validation ExampleValidator_IntRange는 정수 범위 검증을 보여줍니다

package main

import (
	"fmt"

	"github.com/arkd0ng/go-utils/validation"
)

func main() {
	v := validation.New(25, "age")
	v.IntRange(18, 65)
	err := v.Validate()
	if err != nil {
		fmt.Println("Age is out of range")
	} else {
		fmt.Println("Valid age")
	}
}
Output:

Valid age

func (*Validator) JSON

func (v *Validator) JSON() *Validator

JSON validates that the string is valid JSON format. Can validate JSON objects, arrays, strings, numbers, booleans, and null.

JSON은 문자열이 유효한 JSON 형식인지 검증합니다. JSON 객체, 배열, 문자열, 숫자, 불린, null을 검증할 수 있습니다.

Valid JSON Types / 유효한 JSON 타입:

  • Objects: {"key": "value"} 객체: {"key": "value"}
  • Arrays: [1, 2, 3] 배열: [1, 2, 3]
  • Strings: "text" 문자열: "text"
  • Numbers: 123, 12.34 숫자: 123, 12.34
  • Booleans: true, false 불린: true, false
  • Null: null null: null

Valid Examples / 유효한 예:

  • `{"name": "John", "age": 30}`
  • `[1, 2, 3, 4, 5]`
  • `"simple string"`
  • `123.45`
  • `true`
  • `null`

Invalid Examples / 유효하지 않은 예:

  • `{invalid json}` (invalid syntax)
  • `{'key': 'value'}` (single quotes)
  • `{name: "John"}` (unquoted key)
  • “ (empty string)

Returns / 반환:

  • *Validator: Returns self for method chaining 메서드 체이닝을 위해 자신을 반환

Behavior / 동작:

  • Uses json.Unmarshal() for validation json.Unmarshal()을 사용하여 검증
  • Validates JSON syntax only, not schema JSON 문법만 검증하며 스키마는 검증하지 않음
  • Accepts any valid JSON value (not just objects/arrays) 모든 유효한 JSON 값 허용 (객체/배열만이 아님)
  • Skips validation if value is not a string 값이 문자열이 아니면 검증 건너뜀

Use Cases / 사용 사례:

  • API request body validation / API 요청 본문 검증
  • Configuration file validation / 설정 파일 검증
  • JSON payload validation / JSON 페이로드 검증
  • Webhook data validation / 웹훅 데이터 검증

Thread Safety / 스레드 안전성:

  • Thread-safe: No shared state / 스레드 안전: 공유 상태 없음

Performance / 성능:

  • Time complexity: O(n) where n is JSON string length 시간 복잡도: O(n) (n은 JSON 문자열 길이)
  • Full JSON parsing overhead 전체 JSON 파싱 오버헤드
  • Memory allocation for unmarshaling 언마샬링을 위한 메모리 할당

Limitations / 제한사항:

  • Does not validate JSON schema JSON 스키마 검증하지 않음
  • Does not validate specific structure 특정 구조 검증하지 않음
  • Accepts any valid JSON type 모든 유효한 JSON 타입 허용

Example / 예제:

v := validation.New(`{"name": "John"}`, "data")
v.JSON()  // Passes / 성공

v := validation.New(`{invalid}`, "data")
v.JSON()  // Fails / 실패

v := validation.New(`[1, 2, 3]`, "array")
v.JSON()  // Passes / 성공

v := validation.New(`"simple string"`, "text")
v.JSON()  // Passes (valid JSON string) / 성공 (유효한 JSON 문자열)

// API request body / API 요청 본문
v := validation.New(requestBody, "body")
v.Required().JSON()

func (*Validator) JWT

func (v *Validator) JWT() *Validator

JWT validates that the value is a valid JWT (JSON Web Token) format. Validates the three-part structure and base64url encoding.

JWT는 값이 유효한 JWT (JSON Web Token) 형식인지 검증합니다. 세 부분 구조와 base64url 인코딩을 검증합니다.

Parameters / 매개변수:

  • None (operates on validator's value) 없음 (validator의 값에 대해 작동)

Returns / 반환:

  • *Validator: Returns self for method chaining 메서드 체이닝을 위해 자신을 반환

Behavior / 동작:

  • Validates 3-part structure: header.payload.signature 3부분 구조 검증: header.payload.signature
  • Validates base64url encoding base64url 인코딩 검증
  • Checks non-empty parts 비어있지 않은 부분 확인
  • Does not validate JWT signature or expiration JWT 서명이나 만료 검증하지 않음

Use Cases / 사용 사례:

  • API token validation / API 토큰 검증
  • Authentication header parsing / 인증 헤더 파싱
  • OAuth/OpenID Connect / OAuth/OpenID 연결
  • Token format verification / 토큰 형식 확인

Thread Safety / 스레드 안전성:

  • Thread-safe: No shared state / 스레드 안전: 공유 상태 없음

Performance / 성능:

  • Time complexity: O(n), n = token length 시간 복잡도: O(n), n = 토큰 길이
  • Base64 decode for 3 parts 3개 부분에 대한 Base64 디코드

A valid JWT has three parts separated by dots: header.payload.signature Each part is base64url encoded.

유효한 JWT는 점으로 구분된 세 부분으로 구성됩니다: header.payload.signature 각 부분은 base64url로 인코딩됩니다.

Example / 예시:

// Valid JWT / 유효한 JWT
token := "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIn0.dozjgNryP4J3jVmNHl0w5N_XgL0n3I9PlFUP0THsR8U"
v := validation.New(token, "jwt_token")
v.JWT()  // Passes

// With user claims / 사용자 클레임 포함
token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoxMjN9.abc123def"
v = validation.New(token, "auth_token")
v.JWT()  // Passes (format only)

// Invalid - missing part / 무효 - 부분 누락
v = validation.New("header.payload", "token")
v.JWT()  // Fails (only 2 parts)

// Invalid - bad encoding / 무효 - 잘못된 인코딩
v = validation.New("abc.def.ghi", "token")
v.JWT()  // Fails (invalid base64url)

Validation rules / 검증 규칙:

  • Must be a string / 문자열이어야 함
  • Must have exactly 3 parts separated by dots / 점으로 구분된 정확히 3개 부분
  • Each part must be valid base64url encoding / 각 부분은 유효한 base64url 인코딩
  • Header and payload must be non-empty / 헤더와 페이로드는 비어있지 않아야 함
Example

ExampleValidator_JWT demonstrates JWT validation ExampleValidator_JWT는 JWT 검증을 보여줍니다

package main

import (
	"fmt"

	"github.com/arkd0ng/go-utils/validation"
)

func main() {
	token := "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIn0.dozjgNryP4J3jVmNHl0w5N_XgL0n3I9PlFUP0THsR8U"
	v := validation.New(token, "jwt_token")
	v.JWT()

	if len(v.GetErrors()) > 0 {
		fmt.Println("Invalid JWT")
	} else {
		fmt.Println("Valid JWT")
	}
}
Output:

Valid JWT

func (*Validator) Latitude

func (v *Validator) Latitude() *Validator

Latitude validates latitude coordinates (-90 to 90). Accepts numeric types and string representations with automatic conversion.

Latitude는 위도 좌표(-90 ~ 90)를 검증합니다. 자동 변환을 통해 숫자 타입과 문자열 표현을 허용합니다.

Parameters / 매개변수:

  • None (operates on validator's value) 없음 (validator의 값에 대해 작동)

Returns / 반환:

  • *Validator: Returns self for method chaining 메서드 체이닝을 위해 자신을 반환

Behavior / 동작:

  • Accepts float64, float32, int, int64, string float64, float32, int, int64, string 허용
  • Valid range: -90.0 to 90.0 degrees (inclusive) 유효 범위: -90.0 ~ 90.0도 (포함)
  • String values parsed as float64 문자열 값은 float64로 파싱
  • Fails if value not numeric or parseable 값이 숫자가 아니거나 파싱 불가능하면 실패

Use Cases / 사용 사례:

  • GPS coordinate validation / GPS 좌표 검증
  • Location data validation / 위치 데이터 검증
  • Map application input / 지도 애플리케이션 입력
  • Geolocation services / 지오로케이션 서비스

Thread Safety / 스레드 안전성:

  • Thread-safe: No shared state / 스레드 안전: 공유 상태 없음

Performance / 성능:

  • Time complexity: O(1) 시간 복잡도: O(1)
  • Type switch + range check 타입 스위치 + 범위 확인

Valid range: -90.0 to 90.0 degrees 유효 범위: -90.0 ~ 90.0도

Example / 예시:

// Seoul latitude / 서울 위도
v := validation.New(37.5665, "latitude")
v.Latitude()  // Passes

// North Pole / 북극
v = validation.New(90.0, "lat")
v.Latitude()  // Passes

// South Pole / 남극
v = validation.New(-90.0, "lat")
v.Latitude()  // Passes

// String value / 문자열 값
v = validation.New("37.5665", "latitude")
v.Latitude()  // Passes

// Invalid - out of range / 무효 - 범위 밖
v = validation.New(95.0, "latitude")
v.Latitude()  // Fails (> 90)
Example

ExampleValidator_Latitude demonstrates latitude validation ExampleValidator_Latitude는 위도 검증을 보여줍니다

package main

import (
	"fmt"

	"github.com/arkd0ng/go-utils/validation"
)

func main() {
	v := validation.New(37.5665, "latitude")
	v.Latitude()

	if len(v.GetErrors()) > 0 {
		fmt.Println("Invalid latitude")
	} else {
		fmt.Println("Valid latitude")
	}
}
Output:

Valid latitude

func (*Validator) Length

func (v *Validator) Length(n int) *Validator

Length validates that the string has exactly n characters. Uses rune count for accurate Unicode character counting.

Length는 문자열이 정확히 n자인지 검증합니다. 정확한 유니코드 문자 계수를 위해 rune 수를 사용합니다.

Parameters / 매개변수:

  • n: Exact number of characters required 필요한 정확한 문자 수

Returns / 반환:

  • *Validator: Returns self for method chaining 메서드 체이닝을 위해 자신을 반환

Behavior / 동작:

  • Counts Unicode runes, not bytes 바이트가 아닌 유니코드 rune 계산
  • Handles multi-byte characters correctly (emoji, CJK, etc.) 다중 바이트 문자 올바르게 처리 (이모지, 한중일 문자 등)
  • Fails if string length is not exactly n 문자열 길이가 정확히 n이 아니면 실패
  • Skips validation if value is not a string 값이 문자열이 아니면 검증 건너뜀

Use Cases / 사용 사례:

  • Fixed-length codes (postal codes, product codes) 고정 길이 코드 (우편번호, 제품 코드)
  • PIN codes / PIN 코드
  • Verification codes / 인증 코드
  • Country codes (ISO 3166) / 국가 코드 (ISO 3166)

Thread Safety / 스레드 안전성:

  • Thread-safe: No shared state / 스레드 안전: 공유 상태 없음

Performance / 성능:

  • Time complexity: O(n) where n is string length 시간 복잡도: O(n) (n은 문자열 길이)
  • Converts to rune slice (allocates memory) rune 슬라이스로 변환 (메모리 할당)

Example / 예제:

v := validation.New("12345", "zipcode")
v.Length(5)  // Passes / 성공

v := validation.New("1234", "zipcode")
v.Length(5)  // Fails (too short) / 실패 (너무 짧음)

v := validation.New("123456", "zipcode")
v.Length(5)  // Fails (too long) / 실패 (너무 김)

// PIN code validation / PIN 코드 검증
v := validation.New(pin, "pin")
v.Length(4).Numeric()

// Korean phone number (11 digits) / 한국 전화번호 (11자리)
v := validation.New("01012345678", "phone")
v.Length(11).Numeric()

func (*Validator) LessThan

func (v *Validator) LessThan(value float64) *Validator

LessThan validates that the numeric value is strictly less than the given value. Works with all numeric types: int, int8-64, uint, uint8-64, float32, float64.

LessThan은 숫자 값이 주어진 값보다 엄격하게 작은지 검증합니다. 모든 숫자 타입에서 작동합니다: int, int8-64, uint, uint8-64, float32, float64.

Parameters / 매개변수:

  • value: The threshold value (exclusive) 임계값 (미포함)

Returns / 반환:

  • *Validator: Returns self for method chaining 메서드 체이닝을 위해 자신을 반환

Behavior / 동작:

  • Accepts value if val < threshold val < 임계값이면 허용
  • Exclusive comparison (equals fails) 미포함 비교 (같으면 실패)
  • Converts to float64 for comparison 비교를 위해 float64로 변환
  • Fails if value is not numeric 값이 숫자가 아니면 실패

Use Cases / 사용 사례:

  • Maximum threshold validation / 최대 임계값 검증
  • Upper bound validation / 상한 검증
  • Range validation (with GreaterThan) 범위 검증 (GreaterThan과 함께)
  • Negative number validation / 음수 검증

Thread Safety / 스레드 안전성:

  • Thread-safe: No shared state / 스레드 안전: 공유 상태 없음

Performance / 성능:

  • Time complexity: O(1) 시간 복잡도: O(1)
  • Simple numeric comparison 단순 숫자 비교

Comparison with Max() / Max()와의 비교:

  • LessThan(10): value must be < 10 (9, 8, 7...)
  • Max(10): value must be <= 10 (10, 9, 8...)
  • Use LessThan for exclusive upper bounds 미포함 상한에는 LessThan 사용

Example / 예제:

// Exclusive upper bound / 미포함 상한
v := validation.New(5, "score")
v.LessThan(10)  // Passes (5 < 10) / 성공

v := validation.New(10, "score")
v.LessThan(10)  // Fails (10 = 10, not <) / 실패

// Negative validation / 음수 검증
v := validation.New(value, "value")
v.LessThan(0)  // Must be negative

// Open range validation / 열린 범위 검증
v := validation.New(value, "value")
v.GreaterThan(0).LessThan(100)  // 0 < value < 100

func (*Validator) LessThanOrEqual

func (v *Validator) LessThanOrEqual(value float64) *Validator

LessThanOrEqual validates that the numeric value is less than or equal to the given value. Works with all numeric types: int, int8-64, uint, uint8-64, float32, float64.

LessThanOrEqual은 숫자 값이 주어진 값보다 작거나 같은지 검증합니다. 모든 숫자 타입에서 작동합니다: int, int8-64, uint, uint8-64, float32, float64.

Parameters / 매개변수:

  • value: The maximum threshold value (inclusive) 최대 임계값 (포함)

Returns / 반환:

  • *Validator: Returns self for method chaining 메서드 체이닝을 위해 자신을 반환

Behavior / 동작:

  • Accepts value if val <= threshold val <= 임계값이면 허용
  • Inclusive comparison (equals passes) 포함 비교 (같으면 통과)
  • Converts to float64 for comparison 비교를 위해 float64로 변환
  • Fails if value is not numeric 값이 숫자가 아니면 실패

Use Cases / 사용 사례:

  • Maximum value validation / 최대값 검증
  • Upper limit validation / 상한 검증
  • Capacity constraints / 용량 제약
  • Budget limits / 예산 제한

Thread Safety / 스레드 안전성:

  • Thread-safe: No shared state / 스레드 안전: 공유 상태 없음

Performance / 성능:

  • Time complexity: O(1) 시간 복잡도: O(1)
  • Simple numeric comparison 단순 숫자 비교

Comparison with Max() / Max()와의 비교:

  • LessThanOrEqual(10): Same as Max(10)
  • Both accept value <= 10
  • Max() is more idiomatic for maximum bounds 최대 경계에는 Max()가 더 관용적

Example / 예제:

// Inclusive maximum / 포함 최대값
v := validation.New(10, "score")
v.LessThanOrEqual(10)  // Passes (10 <= 10) / 성공

v := validation.New(11, "score")
v.LessThanOrEqual(10)  // Fails (11 > 10) / 실패

// Maximum age / 최대 나이
v := validation.New(age, "age")
v.LessThanOrEqual(120)  // 120 or younger

// Closed range / 닫힌 범위
v := validation.New(value, "value")
v.GreaterThanOrEqual(0).LessThanOrEqual(100)  // 0 <= value <= 100

func (*Validator) Longitude

func (v *Validator) Longitude() *Validator

Longitude validates longitude coordinates (-180 to 180). Accepts numeric types and string representations with automatic conversion.

Longitude는 경도 좌표(-180 ~ 180)를 검증합니다. 자동 변환을 통해 숫자 타입과 문자열 표현을 허용합니다.

Parameters / 매개변수:

  • None (operates on validator's value) 없음 (validator의 값에 대해 작동)

Returns / 반환:

  • *Validator: Returns self for method chaining 메서드 체이닝을 위해 자신을 반환

Behavior / 동작:

  • Accepts float64, float32, int, int64, string float64, float32, int, int64, string 허용
  • Valid range: -180.0 to 180.0 degrees (inclusive) 유효 범위: -180.0 ~ 180.0도 (포함)
  • String values parsed as float64 문자열 값은 float64로 파싱
  • Fails if value not numeric or parseable 값이 숫자가 아니거나 파싱 불가능하면 실패

Use Cases / 사용 사례:

  • GPS coordinate validation / GPS 좌표 검증
  • Location data validation / 위치 데이터 검증
  • Map application input / 지도 애플리케이션 입력
  • Geolocation services / 지오로케이션 서비스

Thread Safety / 스레드 안전성:

  • Thread-safe: No shared state / 스레드 안전: 공유 상태 없음

Performance / 성능:

  • Time complexity: O(1) 시간 복잡도: O(1)
  • Type switch + range check 타입 스위치 + 범위 확인

Valid range: -180.0 to 180.0 degrees 유효 범위: -180.0 ~ 180.0도

Example / 예시:

// Seoul longitude / 서울 경도
v := validation.New(126.9780, "longitude")
v.Longitude()  // Passes

// International Date Line (East) / 국제 날짜 변경선 (동)
v = validation.New(180.0, "lon")
v.Longitude()  // Passes

// International Date Line (West) / 국제 날짜 변경선 (서)
v = validation.New(-180.0, "lon")
v.Longitude()  // Passes

// String value / 문자열 값
v = validation.New("126.9780", "longitude")
v.Longitude()  // Passes

// Invalid - out of range / 무효 - 범위 밖
v = validation.New(185.0, "longitude")
v.Longitude()  // Fails (> 180)
Example

ExampleValidator_Longitude demonstrates longitude validation ExampleValidator_Longitude는 경도 검증을 보여줍니다

package main

import (
	"fmt"

	"github.com/arkd0ng/go-utils/validation"
)

func main() {
	v := validation.New(126.9780, "longitude")
	v.Longitude()

	if len(v.GetErrors()) > 0 {
		fmt.Println("Invalid longitude")
	} else {
		fmt.Println("Valid longitude")
	}
}
Output:

Valid longitude

func (*Validator) Lowercase

func (v *Validator) Lowercase() *Validator

Lowercase validates that all letters in the string are lowercase. Non-letter characters are ignored.

Lowercase는 문자열의 모든 문자가 소문자인지 검증합니다. 문자가 아닌 문자는 무시됩니다.

Character Rules / 문자 규칙:

  • All letters must be lowercase 모든 문자는 소문자여야 함
  • Numbers and symbols are ignored 숫자와 기호는 무시됨
  • Empty string passes validation 빈 문자열은 검증 통과
  • Unicode lowercase letters supported 유니코드 소문자 지원

Valid Examples / 유효한 예:

  • "hello"
  • "hello123"
  • "hello-world"
  • "안녕하세요" (no case distinction)
  • "123" (no letters)

Invalid Examples / 유효하지 않은 예:

  • "Hello" (has uppercase H)
  • "hEllo" (has uppercase E)
  • "HELLO" (all uppercase)
  • "HeLLo123" (mixed case)

Returns / 반환:

  • *Validator: Returns self for method chaining 메서드 체이닝을 위해 자신을 반환

Behavior / 동작:

  • Compares string with its lowercase version 문자열을 소문자 버전과 비교
  • Uses strings.ToLower() for comparison strings.ToLower()를 사용하여 비교
  • Passes if string equals its lowercase form 문자열이 소문자 형태와 같으면 통과
  • Skips validation if value is not a string 값이 문자열이 아니면 검증 건너뜀

Use Cases / 사용 사례:

  • Username format enforcement / 사용자명 형식 강제
  • Email local part validation / 이메일 로컬 부분 검증
  • Lowercase-only fields / 소문자 전용 필드
  • Normalized identifiers / 정규화된 식별자

Thread Safety / 스레드 안전성:

  • Thread-safe: No shared state / 스레드 안전: 공유 상태 없음

Performance / 성능:

  • Time complexity: O(n) where n is string length 시간 복잡도: O(n) (n은 문자열 길이)
  • String allocation for lowercase conversion 소문자 변환을 위한 문자열 할당

Example / 예제:

v := validation.New("hello", "username")
v.Lowercase()  // Passes / 성공

v := validation.New("Hello", "username")
v.Lowercase()  // Fails / 실패

v := validation.New("hello123", "username")
v.Lowercase()  // Passes (numbers ignored) / 성공 (숫자 무시)

v := validation.New("hello-world", "slug")
v.Lowercase()  // Passes (hyphen ignored) / 성공 (하이픈 무시)

// Username validation / 사용자명 검증
v := validation.New(username, "username")
v.Required().Lowercase().Alphanumeric().MinLength(3)

func (*Validator) Luhn

func (v *Validator) Luhn() *Validator

Luhn validates that the value passes the Luhn algorithm checksum verification. Generic Luhn validation for any numeric string (credit cards, IMEI, etc.).

Luhn은 값이 Luhn 알고리즘 체크섬 검증을 통과하는지 검증합니다. 모든 숫자 문자열(신용카드, IMEI 등)에 대한 일반 Luhn 검증입니다.

Parameters / 매개변수:

  • None (operates on validator's value) 없음 (validator의 값에 대해 작동)

Returns / 반환:

  • *Validator: Returns self for method chaining 메서드 체이닝을 위해 자신을 반환

Behavior / 동작:

  • Removes spaces and hyphens before validation 검증 전에 공백과 하이픈 제거
  • Accepts only numeric characters 숫자만 허용
  • Applies Luhn algorithm (mod 10 checksum) Luhn 알고리즘 적용 (mod 10 체크섬)
  • No length restrictions (unlike CreditCard) 길이 제한 없음 (CreditCard와 달리)
  • Fails if value is not string 값이 문자열이 아니면 실패

Algorithm / 알고리즘:

  1. Starting from rightmost digit, double every second digit 가장 오른쪽 숫자부터 시작하여 두 번째 숫자마다 두 배로
  2. If doubling results in > 9, subtract 9 두 배 결과가 9보다 크면 9를 뺌
  3. Sum all digits 모든 숫자 합계
  4. Valid if sum % 10 == 0 합계 % 10 == 0이면 유효

Use Cases / 사용 사례:

  • Credit card validation / 신용카드 검증
  • IMEI number validation / IMEI 번호 검증
  • National ID validation (some countries) / 주민등록번호 검증 (일부 국가)
  • Generic checksum validation / 일반 체크섬 검증

Thread Safety / 스레드 안전성:

  • Thread-safe: No shared state / 스레드 안전: 공유 상태 없음

Performance / 성능:

  • Time complexity: O(n), n = number length 시간 복잡도: O(n), n = 번호 길이
  • Single pass algorithm 단일 패스 알고리즘

Example / 예제:

// Valid Luhn numbers / 유효한 Luhn 번호
v := validation.New("79927398713", "number")
v.Luhn()  // Passes (valid checksum)

// Credit card number / 신용카드 번호
v = validation.New("4532015112830366", "card")
v.Luhn()  // Passes

// With formatting / 형식 포함
v = validation.New("4532-0151-1283-0366", "card")
v.Luhn()  // Passes (hyphens removed)

// Invalid checksum / 무효한 체크섬
v = validation.New("79927398714", "number")
v.Luhn()  // Fails (checksum error)
Example

ExampleValidator_Luhn demonstrates Luhn algorithm validation ExampleValidator_Luhn는 Luhn 알고리즘 검증을 보여줍니다

package main

import (
	"fmt"

	"github.com/arkd0ng/go-utils/validation"
)

func main() {
	v := validation.New("79927398713", "identifier")
	v.Luhn()

	if len(v.GetErrors()) > 0 {
		fmt.Println("Invalid Luhn number")
	} else {
		fmt.Println("Valid Luhn number")
	}
}
Output:

Valid Luhn number

func (*Validator) MAC

func (v *Validator) MAC() *Validator

MAC validates that the value is a valid MAC address. Supports multiple MAC address formats with case-insensitive validation.

MAC는 값이 유효한 MAC 주소인지 검증합니다. 대소문자 구분 없는 검증으로 여러 MAC 주소 형식을 지원합니다.

Parameters / 매개변수:

  • None (operates on validator's value) 없음 (validator의 값에 대해 작동)

Returns / 반환:

  • *Validator: Returns self for method chaining 메서드 체이닝을 위해 자신을 반환

Behavior / 동작:

  • Uses net.ParseMAC for validation 검증을 위해 net.ParseMAC 사용
  • Supports colon-separated format (00:1A:2B:3C:4D:5E) 콜론 구분 형식 지원 (00:1A:2B:3C:4D:5E)
  • Supports hyphen-separated format (00-1A-2B-3C-4D-5E) 하이픈 구분 형식 지원 (00-1A-2B-3C-4D-5E)
  • Supports dot-separated format (001A.2B3C.4D5E - Cisco) 점 구분 형식 지원 (001A.2B3C.4D5E - Cisco)
  • Case-insensitive validation 대소문자 구분 없는 검증
  • Fails if value is not string 값이 문자열이 아니면 실패

Use Cases / 사용 사례:

  • Network device identification / 네트워크 장치 식별
  • Hardware address validation / 하드웨어 주소 검증
  • Network configuration / 네트워크 구성
  • Device registration / 장치 등록

Thread Safety / 스레드 안전성:

  • Thread-safe: No shared state / 스레드 안전: 공유 상태 없음

Performance / 성능:

  • Time complexity: O(n), n = string length 시간 복잡도: O(n), n = 문자열 길이
  • Single net.ParseMAC call 단일 net.ParseMAC 호출

Supports multiple MAC address formats / 여러 MAC 주소 형식 지원: - Colon-separated: 00:1A:2B:3C:4D:5E - Hyphen-separated: 00-1A-2B-3C-4D-5E - Dot-separated: 001A.2B3C.4D5E (Cisco format)

The validation is case-insensitive.

Example / 예제:

// Colon-separated (common) / 콜론 구분 (일반)
v := validation.New("00:1A:2B:3C:4D:5E", "mac_address")
v.MAC()  // Passes

// Hyphen-separated / 하이픈 구분
v = validation.New("00-1a-2b-3c-4d-5e", "mac_address")
v.MAC()  // Passes (case-insensitive)

// Cisco format (dot-separated) / Cisco 형식 (점 구분)
v = validation.New("001A.2B3C.4D5E", "mac_address")
v.MAC()  // Passes

// Case variations / 대소문자 변형
v = validation.New("AA:BB:CC:DD:EE:FF", "mac")
v.MAC()  // Passes

// Invalid MAC / 무효한 MAC
v = validation.New("GG:HH:II:JJ:KK:LL", "mac")
v.MAC()  // Fails (invalid hex)

v = validation.New("00:1A:2B:3C:4D", "mac")
v.MAC()  // Fails (too short)
Example

ExampleValidator_MAC demonstrates the MAC validator ExampleValidator_MAC는 MAC 검증기를 보여줍니다

package main

import (
	"fmt"

	"github.com/arkd0ng/go-utils/validation"
)

func main() {
	v := validation.New("00:1A:2B:3C:4D:5E", "mac_address")
	v.MAC()
	err := v.Validate()
	if err != nil {
		fmt.Println("Invalid MAC address")
	} else {
		fmt.Println("Valid MAC address")
	}
}
Output:

Valid MAC address

func (*Validator) MD5

func (v *Validator) MD5() *Validator

MD5 validates that the value is a valid MD5 hash (32 hexadecimal characters). MD5 produces 128-bit hash values typically represented as 32 hexadecimal digits.

MD5는 값이 유효한 MD5 해시(32자리 16진수)인지 검증합니다. MD5는 일반적으로 32자리 16진수로 표현되는 128비트 해시 값을 생성합니다.

Parameters / 매개변수:

  • None (operates on validator's value) 없음 (validator의 값에 대해 작동)

Returns / 반환:

  • *Validator: Returns self for method chaining 메서드 체이닝을 위해 자신을 반환

Behavior / 동작:

  • Validates 32-character length 32자 길이 검증
  • Validates hexadecimal characters (0-9, a-f, A-F) 16진수 문자 검증 (0-9, a-f, A-F)
  • Case-insensitive 대소문자 구분 안 함
  • Does not validate hash correctness 해시 정확성 검증하지 않음

Use Cases / 사용 사례:

  • File integrity checking / 파일 무결성 확인
  • Hash format validation / 해시 형식 검증
  • Checksum verification / 체크섬 확인
  • Legacy system compatibility / 레거시 시스템 호환성

Thread Safety / 스레드 안전성:

  • Thread-safe: No shared state / 스레드 안전: 공유 상태 없음

Performance / 성능:

  • Time complexity: O(1), fixed length regex 시간 복잡도: O(1), 고정 길이 정규식
  • Simple pattern matching 간단한 패턴 매칭

Note: MD5 is cryptographically broken and should not be used for security purposes. Use SHA256 or stronger algorithms for security-critical applications.

참고: MD5는 암호학적으로 취약하며 보안 목적으로 사용해서는 안 됩니다. 보안이 중요한 애플리케이션에는 SHA256 이상의 강력한 알고리즘을 사용하세요.

Example / 예시:

// Valid MD5 hash / 유효한 MD5 해시
hash := "5d41402abc4b2a76b9719d911017c592"
v := validation.New(hash, "file_hash")
v.MD5()  // Passes

// Uppercase hex / 대문자 16진수
hash = "5D41402ABC4B2A76B9719D911017C592"
v = validation.New(hash, "hash")
v.MD5()  // Passes

// Invalid - wrong length / 무효 - 잘못된 길이
v = validation.New("5d41402abc4b2a76", "hash")
v.MD5()  // Fails (too short)

// Invalid - non-hex characters / 무효 - 16진수가 아닌 문자
v = validation.New("5d41402abc4b2a76b9719d911017c59z", "hash")
v.MD5()  // Fails (contains 'z')

Validation rules / 검증 규칙:

  • Must be a string / 문자열이어야 함
  • Must be exactly 32 characters / 정확히 32자여야 함
  • Must contain only hexadecimal characters (0-9, a-f, A-F) / 16진수 문자만 포함
Example

ExampleValidator_MD5 demonstrates MD5 hash validation ExampleValidator_MD5는 MD5 해시 검증을 보여줍니다

package main

import (
	"fmt"

	"github.com/arkd0ng/go-utils/validation"
)

func main() {
	hash := "5d41402abc4b2a76b9719d911017c592"
	v := validation.New(hash, "file_hash")
	v.MD5()

	if len(v.GetErrors()) > 0 {
		fmt.Println("Invalid MD5")
	} else {
		fmt.Println("Valid MD5")
	}
}
Output:

Valid MD5

func (*Validator) MapHasKey

func (v *Validator) MapHasKey(key interface{}) *Validator

MapHasKey validates that the map contains the specified key. Fails if value is not a map type or if the key is not found.

MapHasKey는 맵이 지정된 키를 포함하는지 검증합니다. 값이 맵 타입이 아니거나 키를 찾지 못하면 실패합니다.

Parameters / 매개변수:

  • key: The key that must exist in the map 맵에 존재해야 하는 키

Returns / 반환:

  • *Validator: Returns self for method chaining 메서드 체이닝을 위해 자신을 반환

Behavior / 동작:

  • Uses reflection to check map key existence 반사를 사용하여 맵 키 존재 확인
  • Works with any map type 모든 맵 타입에서 작동
  • Fails if not a map type 맵 타입이 아니면 실패
  • Fails if key not found 키를 찾지 못하면 실패
  • Does not validate the value associated with the key 키와 연관된 값은 검증하지 않음

Use Cases / 사용 사례:

  • Required configuration keys / 필수 설정 키
  • API request body validation / API 요청 본문 검증
  • JSON/struct field presence / JSON/구조체 필드 존재
  • Required metadata / 필수 메타데이터
  • Config validation / 설정 검증

Thread Safety / 스레드 안전성:

  • Thread-safe: No shared state / 스레드 안전: 공유 상태 없음

Performance / 성능:

  • Time complexity: O(1) average for hash map 시간 복잡도: 해시 맵 평균 O(1)
  • Reflection overhead for type checking 타입 검사를 위한 반사 오버헤드

Example / 예제:

// Single key check / 단일 키 확인
v := validation.New(map[string]int{"age": 25}, "data")
v.MapHasKey("age")  // Passes / 성공

v := validation.New(map[string]int{"name": 1}, "data")
v.MapHasKey("age")  // Fails / 실패

// Configuration validation / 설정 검증
v := validation.New(config, "config")
v.MapHasKey("database_url")

// API request / API 요청
v := validation.New(requestData, "request")
v.MapNotEmpty().MapHasKey("user_id")

// Different key types / 다른 키 타입
v := validation.New(map[int]string{1: "one"}, "data")
v.MapHasKey(1)  // Passes / 성공
Example

ExampleValidator_MapHasKey demonstrates the MapHasKey validator ExampleValidator_MapHasKey는 MapHasKey 검증기를 보여줍니다

package main

import (
	"fmt"

	"github.com/arkd0ng/go-utils/validation"
)

func main() {
	data := map[string]int{"age": 25, "score": 100}
	v := validation.New(data, "data")
	v.MapHasKey("age")
	err := v.Validate()
	if err != nil {
		fmt.Println("Key not found")
	} else {
		fmt.Println("Key exists")
	}
}
Output:

Key exists

func (*Validator) MapHasKeys

func (v *Validator) MapHasKeys(keys ...interface{}) *Validator

MapHasKeys validates that the map contains all of the specified keys. Fails if value is not a map type or if any required key is missing.

MapHasKeys는 맵이 지정된 모든 키를 포함하는지 검증합니다. 값이 맵 타입이 아니거나 필수 키가 하나라도 없으면 실패합니다.

Parameters / 매개변수:

  • keys: Variadic list of keys that must all exist 모두 존재해야 하는 키들의 가변 인자 목록

Returns / 반환:

  • *Validator: Returns self for method chaining 메서드 체이닝을 위해 자신을 반환

Behavior / 동작:

  • Uses reflection to check map key existence 반사를 사용하여 맵 키 존재 확인
  • Works with any map type 모든 맵 타입에서 작동
  • Fails if not a map type 맵 타입이 아니면 실패
  • Fails if any key is missing 키가 하나라도 없으면 실패
  • Lists all missing keys in error message 오류 메시지에 모든 누락된 키 나열
  • Does not validate the values associated with keys 키와 연관된 값은 검증하지 않음

Use Cases / 사용 사례:

  • Required configuration keys / 필수 설정 키들
  • API request body validation / API 요청 본문 검증
  • Required struct fields / 필수 구조체 필드들
  • Complete data validation / 완전한 데이터 검증
  • Schema validation / 스키마 검증

Thread Safety / 스레드 안전성:

  • Thread-safe: No shared state / 스레드 안전: 공유 상태 없음

Performance / 성능:

  • Time complexity: O(k) where k is number of keys to check 시간 복잡도: O(k) (k는 확인할 키의 수)
  • Each key lookup is O(1) average 각 키 조회는 평균 O(1)
  • Reflection overhead for type checking 타입 검사를 위한 반사 오버헤드

Example / 예제:

// Multiple keys / 여러 키
v := validation.New(map[string]string{"name": "John", "email": "j@e.com"}, "user")
v.MapHasKeys("name", "email")  // Passes / 성공

v := validation.New(map[string]string{"name": "John"}, "user")
v.MapHasKeys("name", "email")  // Fails (missing email) / 실패 (email 누락)

// Configuration validation / 설정 검증
v := validation.New(config, "config")
v.MapNotEmpty().MapHasKeys("host", "port", "database")

// API request / API 요청
v := validation.New(requestData, "request")
v.MapHasKeys("user_id", "action", "timestamp")

// Error message shows all missing keys
// 오류 메시지는 모든 누락된 키 표시
data := map[string]int{"a": 1}
v := validation.New(data, "data")
v.MapHasKeys("a", "b", "c")  // Error: missing keys: [b c]
Example

ExampleValidator_MapHasKeys demonstrates the MapHasKeys validator ExampleValidator_MapHasKeys는 MapHasKeys 검증기를 보여줍니다

package main

import (
	"fmt"

	"github.com/arkd0ng/go-utils/validation"
)

func main() {
	data := map[string]int{"name": 1, "age": 25, "city": 3}
	v := validation.New(data, "data")
	v.MapHasKeys("name", "age")
	err := v.Validate()
	if err != nil {
		fmt.Println("Missing required keys")
	} else {
		fmt.Println("All keys present")
	}
}
Output:

All keys present

func (*Validator) MapNotEmpty

func (v *Validator) MapNotEmpty() *Validator

MapNotEmpty validates that the map is not empty (has at least one key-value pair). Fails if value is not a map type or if the map has no entries.

MapNotEmpty는 맵이 비어있지 않은지 (최소 하나의 키-값 쌍 포함) 검증합니다. 값이 맵 타입이 아니거나 맵에 항목이 없으면 실패합니다.

Returns / 반환:

  • *Validator: Returns self for method chaining 메서드 체이닝을 위해 자신을 반환

Behavior / 동작:

  • Uses reflection to check map length 반사를 사용하여 맵 길이 확인
  • Works with any map type 모든 맵 타입에서 작동
  • Fails if not a map type 맵 타입이 아니면 실패
  • Fails if map length is zero 맵 길이가 0이면 실패

Use Cases / 사용 사례:

  • Required data validation / 필수 데이터 검증
  • Non-empty configuration / 비어있지 않은 설정
  • API response validation / API 응답 검증
  • Metadata presence / 메타데이터 존재
  • Parameter validation / 매개변수 검증

Thread Safety / 스레드 안전성:

  • Thread-safe: No shared state / 스레드 안전: 공유 상태 없음

Performance / 성능:

  • Time complexity: O(1) 시간 복잡도: O(1)
  • Reflection overhead for type checking 타입 검사를 위한 반사 오버헤드

Note / 참고:

  • Does not validate specific keys or values 특정 키나 값은 검증하지 않음
  • Only checks that map has at least one entry 맵에 최소 하나의 항목이 있는지만 확인
  • Use MapHasKeys for specific key validation 특정 키 검증은 MapHasKeys 사용

Example / 예제:

// Non-empty map / 비어있지 않은 맵
v := validation.New(map[string]int{"count": 1}, "data")
v.MapNotEmpty()  // Passes / 성공

v := validation.New(map[string]int{}, "data")
v.MapNotEmpty()  // Fails / 실패

// Configuration validation / 설정 검증
v := validation.New(config, "config")
v.MapNotEmpty()

// API request data / API 요청 데이터
v := validation.New(requestData, "data")
v.MapNotEmpty().MapHasKeys("action")

// Metadata validation / 메타데이터 검증
v := validation.New(metadata, "metadata")
v.MapNotEmpty()

// Nil map check / nil 맵 확인
var nilMap map[string]int
v := validation.New(nilMap, "data")
v.MapNotEmpty()  // Fails (nil map has length 0) / 실패 (nil 맵은 길이 0)

func (*Validator) Max

func (v *Validator) Max(n float64) *Validator

Max validates that the numeric value is less than or equal to the maximum threshold. Works with all numeric types: int, int8-64, uint, uint8-64, float32, float64.

Max는 숫자 값이 최대 임계값 이하인지 검증합니다. 모든 숫자 타입에서 작동합니다: int, int8-64, uint, uint8-64, float32, float64.

Parameters / 매개변수:

  • n: Maximum value (inclusive) 최대값 (포함)

Returns / 반환:

  • *Validator: Returns self for method chaining 메서드 체이닝을 위해 자신을 반환

Behavior / 동작:

  • Accepts value if val <= n val <= n이면 허용
  • Converts value to float64 for comparison 비교를 위해 값을 float64로 변환
  • Inclusive comparison (equals is valid) 포함 비교 (같음은 유효)
  • Skips validation if value is not numeric 값이 숫자가 아니면 검증 건너뜀

Use Cases / 사용 사례:

  • Age validation (maximum age) 나이 검증 (최대 나이)
  • Price caps / 가격 상한
  • Quantity limits / 수량 제한
  • Score/rating upper bounds / 점수/평점 상한
  • Database column constraints / 데이터베이스 컬럼 제약

Thread Safety / 스레드 안전성:

  • Thread-safe: No shared state / 스레드 안전: 공유 상태 없음

Performance / 성능:

  • Time complexity: O(1) 시간 복잡도: O(1)
  • Simple numeric comparison 단순 숫자 비교

Example / 예제:

v := validation.New(15, "age")
v.Max(18)  // Passes / 성공

v := validation.New(25, "age")
v.Max(18)  // Fails / 실패

v := validation.New(18, "age")
v.Max(18)  // Passes (inclusive) / 성공 (포함)

// Percentage validation / 백분율 검증
v := validation.New(percentage, "discount")
v.Min(0).Max(100)

// Rating validation / 평점 검증
v := validation.New(rating, "rating")
v.Positive().Min(1).Max(5)
Example

ExampleValidator_Max demonstrates the Max validator ExampleValidator_Max는 Max 검증기를 보여줍니다

package main

import (
	"fmt"

	"github.com/arkd0ng/go-utils/validation"
)

func main() {
	v := validation.New(150, "age")
	v.Max(120)
	err := v.Validate()
	if err != nil {
		fmt.Println("Age exceeds maximum")
	}
}
Output:

Age exceeds maximum

func (*Validator) MaxLength

func (v *Validator) MaxLength(n int) *Validator

MaxLength validates that the string has at most n characters. Uses rune count for accurate Unicode character counting.

MaxLength는 문자열이 최대 n자 이하인지 검증합니다. 정확한 유니코드 문자 계수를 위해 rune 수를 사용합니다.

Parameters / 매개변수:

  • n: Maximum number of characters allowed 허용되는 최대 문자 수

Returns / 반환:

  • *Validator: Returns self for method chaining 메서드 체이닝을 위해 자신을 반환

Behavior / 동작:

  • Counts Unicode runes, not bytes 바이트가 아닌 유니코드 rune 계산
  • Handles multi-byte characters correctly (emoji, CJK, etc.) 다중 바이트 문자 올바르게 처리 (이모지, 한중일 문자 등)
  • Fails if string has more than n characters n자보다 많으면 실패
  • Skips validation if value is not a string 값이 문자열이 아니면 검증 건너뜀

Use Cases / 사용 사례:

  • Database column length constraints / 데이터베이스 컬럼 길이 제약
  • Username maximum length / 사용자명 최대 길이
  • Tweet/message length limits / 트윗/메시지 길이 제한
  • Form field restrictions / 폼 필드 제한

Thread Safety / 스레드 안전성:

  • Thread-safe: No shared state / 스레드 안전: 공유 상태 없음

Performance / 성능:

  • Time complexity: O(n) where n is string length 시간 복잡도: O(n) (n은 문자열 길이)
  • Converts to rune slice (allocates memory) rune 슬라이스로 변환 (메모리 할당)

Example / 예제:

v := validation.New("TooLongMessage", "message")
v.MaxLength(5)  // Fails / 실패

v := validation.New("Short", "message")
v.MaxLength(10)  // Passes / 성공

v := validation.New("안녕하세요반갑습니다", "greeting")
v.MaxLength(5)  // Fails (10 runes) / 실패 (10 rune)

// Database VARCHAR(50) constraint / 데이터베이스 VARCHAR(50) 제약
v := validation.New(username, "username")
v.Required().MaxLength(50)
Example

ExampleValidator_MaxLength demonstrates the MaxLength validator ExampleValidator_MaxLength는 MaxLength 검증기를 보여줍니다

package main

import (
	"fmt"

	"github.com/arkd0ng/go-utils/validation"
)

func main() {
	v := validation.New("short", "username")
	v.MaxLength(20)
	err := v.Validate()
	if err != nil {
		fmt.Println("Error: username too long")
	} else {
		fmt.Println("Valid username")
	}
}
Output:

Valid username

func (*Validator) Min

func (v *Validator) Min(n float64) *Validator

Min validates that the numeric value is greater than or equal to the minimum threshold. Works with all numeric types: int, int8-64, uint, uint8-64, float32, float64.

Min은 숫자 값이 최소 임계값 이상인지 검증합니다. 모든 숫자 타입에서 작동합니다: int, int8-64, uint, uint8-64, float32, float64.

Parameters / 매개변수:

  • n: Minimum value (inclusive) 최소값 (포함)

Returns / 반환:

  • *Validator: Returns self for method chaining 메서드 체이닝을 위해 자신을 반환

Behavior / 동작:

  • Accepts value if val >= n val >= n이면 허용
  • Converts value to float64 for comparison 비교를 위해 값을 float64로 변환
  • Inclusive comparison (equals is valid) 포함 비교 (같음은 유효)
  • Skips validation if value is not numeric 값이 숫자가 아니면 검증 건너뜀

Use Cases / 사용 사례:

  • Age validation (minimum age) 나이 검증 (최소 나이)
  • Price validation (minimum price) 가격 검증 (최소 가격)
  • Quantity validation / 수량 검증
  • Score/rating thresholds / 점수/평점 임계값

Thread Safety / 스레드 안전성:

  • Thread-safe: No shared state / 스레드 안전: 공유 상태 없음

Performance / 성능:

  • Time complexity: O(1) 시간 복잡도: O(1)
  • Simple numeric comparison 단순 숫자 비교

Example / 예제:

v := validation.New(25, "age")
v.Min(18)  // Passes / 성공

v := validation.New(15, "age")
v.Min(18)  // Fails / 실패

v := validation.New(18, "age")
v.Min(18)  // Passes (inclusive) / 성공 (포함)

// Price validation / 가격 검증
v := validation.New(price, "price")
v.Positive().Min(0.01).Max(99999.99)

// Age requirement / 나이 요구사항
v := validation.New(age, "age")
v.Required().Min(18).Max(120)
Example

ExampleValidator_Min demonstrates the Min validator ExampleValidator_Min는 Min 검증기를 보여줍니다

package main

import (
	"fmt"

	"github.com/arkd0ng/go-utils/validation"
)

func main() {
	v := validation.New(25, "age")
	v.Min(18)
	err := v.Validate()
	if err != nil {
		fmt.Println("Too young")
	} else {
		fmt.Println("Valid age")
	}
}
Output:

Valid age

func (*Validator) MinLength

func (v *Validator) MinLength(n int) *Validator

MinLength validates that the string has at least n characters. Uses rune count for accurate Unicode character counting.

MinLength는 문자열이 최소 n자 이상인지 검증합니다. 정확한 유니코드 문자 계수를 위해 rune 수를 사용합니다.

Parameters / 매개변수:

  • n: Minimum number of characters required 필요한 최소 문자 수

Returns / 반환:

  • *Validator: Returns self for method chaining 메서드 체이닝을 위해 자신을 반환

Behavior / 동작:

  • Counts Unicode runes, not bytes 바이트가 아닌 유니코드 rune 계산
  • Handles multi-byte characters correctly (emoji, CJK, etc.) 다중 바이트 문자 올바르게 처리 (이모지, 한중일 문자 등)
  • Fails if string has fewer than n characters n자보다 적으면 실패
  • Skips validation if value is not a string 값이 문자열이 아니면 검증 건너뜀

Use Cases / 사용 사례:

  • Password length validation / 비밀번호 길이 검증
  • Username minimum length / 사용자명 최소 길이
  • Comment/description length / 댓글/설명 길이
  • International text input / 국제 텍스트 입력

Thread Safety / 스레드 안전성:

  • Thread-safe: No shared state / 스레드 안전: 공유 상태 없음

Performance / 성능:

  • Time complexity: O(n) where n is string length 시간 복잡도: O(n) (n은 문자열 길이)
  • Converts to rune slice (allocates memory) rune 슬라이스로 변환 (메모리 할당)

Example / 예제:

v := validation.New("Hi", "message")
v.MinLength(5)  // Fails / 실패

v := validation.New("Hello", "message")
v.MinLength(5)  // Passes / 성공

v := validation.New("안녕하세요", "greeting")
v.MinLength(3)  // Passes (5 runes) / 성공 (5 rune)

// With multi-byte characters / 다중 바이트 문자
v := validation.New("👋🌍", "emoji")
v.MinLength(2)  // Passes (2 runes) / 성공 (2 rune)
Example

ExampleValidator_MinLength demonstrates the MinLength validator ExampleValidator_MinLength는 MinLength 검증기를 보여줍니다

package main

import (
	"fmt"

	"github.com/arkd0ng/go-utils/validation"
)

func main() {
	v := validation.New("abc", "password")
	v.MinLength(8)
	err := v.Validate()
	if err != nil {
		fmt.Println("Error: password too short")
	}
}
Output:

Error: password too short

func (*Validator) MultipleOf

func (v *Validator) MultipleOf(n float64) *Validator

MultipleOf validates that the numeric value is a multiple of the specified number. Converts both values to integers before checking divisibility.

MultipleOf는 숫자 값이 지정된 숫자의 배수인지 검증합니다. 나누기 가능성 검사 전 두 값을 정수로 변환합니다.

Parameters / 매개변수:

  • n: The divisor (must not be zero) 제수 (0이면 안 됨)

Returns / 반환:

  • *Validator: Returns self for method chaining 메서드 체이닝을 위해 자신을 반환

Behavior / 동작:

  • Converts both value and n to int 값과 n을 모두 int로 변환
  • Fails if n is zero (division by zero) n이 0이면 실패 (0으로 나누기)
  • Uses modulo operation: val % n == 0 나머지 연산 사용: val % n == 0
  • Truncates decimal parts 소수 부분 버림
  • Skips validation if value is not numeric 값이 숫자가 아니면 검증 건너뜀

Use Cases / 사용 사례:

  • Batch size validation (multiples of 10, 100) 배치 크기 검증 (10, 100의 배수)
  • Increment validation / 증분 검증
  • Package quantity (multiples of 6, 12) 패키지 수량 (6, 12의 배수)
  • Time intervals (multiples of 5, 15, 30) 시간 간격 (5, 15, 30의 배수)

Thread Safety / 스레드 안전성:

  • Thread-safe: No shared state / 스레드 안전: 공유 상태 없음

Performance / 성능:

  • Time complexity: O(1) 시간 복잡도: O(1)
  • Single modulo operation 단일 나머지 연산

Important Note / 중요 참고:

  • Both value and n are converted to int 값과 n 모두 int로 변환
  • Float precision is lost (10.5, 2.5 -> 10, 2) 부동 소수점 정밀도 손실 (10.5, 2.5 -> 10, 2)
  • n = 0 always returns false (no division by zero) n = 0은 항상 false 반환 (0으로 나누기 없음)

Example / 예제:

v := validation.New(10, "quantity")
v.MultipleOf(5)  // Passes (10 = 5 * 2) / 성공

v := validation.New(12, "quantity")
v.MultipleOf(5)  // Fails / 실패

v := validation.New(0, "value")
v.MultipleOf(5)  // Passes (0 = 5 * 0) / 성공

v := validation.New(15, "minutes")
v.MultipleOf(15)  // Passes / 성공

v := validation.New(10, "value")
v.MultipleOf(0)  // Fails (division by zero) / 실패 (0으로 나누기)

// Batch size / 배치 크기
v := validation.New(quantity, "batch_size")
v.Positive().MultipleOf(100)

// Time interval in minutes / 분 단위 시간 간격
v := validation.New(minutes, "interval")
v.Between(0, 60).MultipleOf(5)

func (*Validator) Negative

func (v *Validator) Negative() *Validator

Negative validates that the numeric value is strictly less than zero. Works with all numeric types: int, int8-64, uint, uint8-64, float32, float64.

Negative는 숫자 값이 0보다 엄격하게 작은지 검증합니다. 모든 숫자 타입에서 작동합니다: int, int8-64, uint, uint8-64, float32, float64.

Returns / 반환:

  • *Validator: Returns self for method chaining 메서드 체이닝을 위해 자신을 반환

Behavior / 동작:

  • Accepts value if val < 0 val < 0이면 허용
  • Zero is NOT valid (use NonZero for zero/negative) 0은 유효하지 않음 (0/음수는 NonZero 사용)
  • Converts value to float64 for comparison 비교를 위해 값을 float64로 변환
  • Skips validation if value is not numeric 값이 숫자가 아니면 검증 건너뜀

Use Cases / 사용 사례:

  • Debt/loss values / 부채/손실 값
  • Temperature below zero / 영하 온도
  • Negative offsets / 음수 오프셋
  • Coordinate systems (negative axes) 좌표계 (음수 축)
  • Financial losses / 재무 손실

Thread Safety / 스레드 안전성:

  • Thread-safe: No shared state / 스레드 안전: 공유 상태 없음

Performance / 성능:

  • Time complexity: O(1) 시간 복잡도: O(1)
  • Single numeric comparison 단일 숫자 비교

Example / 예제:

v := validation.New(-10, "loss")
v.Negative()  // Passes / 성공

v := validation.New(0, "loss")
v.Negative()  // Fails (zero not negative) / 실패 (0은 음수 아님)

v := validation.New(5, "loss")
v.Negative()  // Fails / 실패

v := validation.New(-0.01, "adjustment")
v.Negative()  // Passes / 성공

// Financial loss / 재무 손실
v := validation.New(loss, "loss")
v.Negative().Max(-0.01)

// Temperature below freezing / 빙점 이하 온도
v := validation.New(temp, "temperature")
v.Negative().Between(-50, -0.01)

func (*Validator) Nil

func (v *Validator) Nil() *Validator

Nil validates that the value is nil. Uses reflection to check nil pointers, interfaces, slices, maps, channels, and functions.

Nil은 값이 nil인지 검증합니다. 리플렉션을 사용하여 nil 포인터, 인터페이스, 슬라이스, 맵, 채널 및 함수를 확인합니다.

Parameters / 매개변수:

  • None (operates on validator's value) 없음 (validator의 값에 대해 작동)

Returns / 반환:

  • *Validator: Returns self for method chaining 메서드 체이닝을 위해 자신을 반환

Behavior / 동작:

  • Accepts nil value nil 값 허용
  • Checks nil pointers via reflection 리플렉션을 통한 nil 포인터 확인
  • Supports: pointer, interface, slice, map, channel, func 지원: 포인터, 인터페이스, 슬라이스, 맵, 채널, 함수
  • Fails on non-nil values nil이 아닌 값에 실패

Use Cases / 사용 사례:

  • Optional field validation / 선택적 필드 검증
  • Null state verification / null 상태 확인
  • Pointer absence check / 포인터 부재 확인
  • Resource cleanup validation / 리소스 정리 검증

Thread Safety / 스레드 안전성:

  • Thread-safe: No shared state / 스레드 안전: 공유 상태 없음

Performance / 성능:

  • Time complexity: O(1) 시간 복잡도: O(1)
  • Reflection-based nil check 리플렉션 기반 nil 확인

This validator checks if the value is nil (pointer, interface, slice, map, channel, func). Useful for validating optional fields that should be nil. 이 검증기는 값이 nil인지 확인합니다 (포인터, 인터페이스, 슬라이스, 맵, 채널, 함수). nil이어야 하는 선택적 필드를 검증하는 데 유용합니다.

Example / 예시:

// Valid - nil pointer / 유효 - nil 포인터
var ptr *string
v := validation.New(ptr, "optional")
v.Nil()  // Passes

// Valid - nil slice / 유효 - nil 슬라이스
var slice []int
v = validation.New(slice, "data")
v.Nil()  // Passes

// Invalid - non-nil / 무효 - nil 아님
str := "value"
v = validation.New(&str, "ptr")
v.Nil()  // Fails

// Invalid - value type / 무효 - 값 타입
v = validation.New(42, "number")
v.Nil()  // Fails (not nillable type)

Validation rules / 검증 규칙:

  • Value must be nil / 값이 nil이어야 함
  • Works with pointers, interfaces, slices, maps, channels, functions
Example

ExampleValidator_Nil demonstrates nil value validation. ExampleValidator_Nil는 nil 값 검증을 보여줍니다.

package main

import (
	"fmt"

	"github.com/arkd0ng/go-utils/validation"
)

func main() {
	// Validate optional field is nil
	var optionalField *string
	v := validation.New(optionalField, "optional_field")
	v.Nil()

	err := v.Validate()
	if err != nil {
		fmt.Println("Field should be nil")
	} else {
		fmt.Println("Field is correctly nil")
	}
}
Output:

Field is correctly nil

func (*Validator) NonZero

func (v *Validator) NonZero() *Validator

NonZero validates that the numeric value is not equal to zero. Works with all numeric types: int, int8-64, uint, uint8-64, float32, float64.

NonZero는 숫자 값이 0이 아닌지 검증합니다. 모든 숫자 타입에서 작동합니다: int, int8-64, uint, uint8-64, float32, float64.

Returns / 반환:

  • *Validator: Returns self for method chaining 메서드 체이닝을 위해 자신을 반환

Behavior / 동작:

  • Accepts value if val != 0 val != 0이면 허용
  • Accepts both positive and negative values 양수와 음수 모두 허용
  • Converts value to float64 for comparison 비교를 위해 값을 float64로 변환
  • Skips validation if value is not numeric 값이 숫자가 아니면 검증 건너뜀

Use Cases / 사용 사례:

  • Ensure value has been set / 값이 설정되었는지 확인
  • Prevent division by zero / 0으로 나누기 방지
  • Non-default value validation / 비기본값 검증
  • Active state verification / 활성 상태 확인
  • Required numeric value / 필수 숫자 값

Thread Safety / 스레드 안전성:

  • Thread-safe: No shared state / 스레드 안전: 공유 상태 없음

Performance / 성능:

  • Time complexity: O(1) 시간 복잡도: O(1)
  • Single numeric comparison 단일 숫자 비교

Example / 예제:

v := validation.New(10, "divisor")
v.NonZero()  // Passes / 성공

v := validation.New(-5, "divisor")
v.NonZero()  // Passes / 성공

v := validation.New(0, "divisor")
v.NonZero()  // Fails / 실패

v := validation.New(0.001, "factor")
v.NonZero()  // Passes / 성공

// Division safety / 나누기 안전성
v := validation.New(divisor, "divisor")
v.NonZero() // Prevent division by zero

// Quantity must be set / 수량 설정 필수
v := validation.New(quantity, "quantity")
v.NonZero().Positive()

func (*Validator) NotEmpty

func (v *Validator) NotEmpty() *Validator

NotEmpty validates that the value is not empty (not zero value). Ensures value is not the zero value for its type, works across all types.

NotEmpty는 값이 비어있지 않은지 (제로 값이 아닌지) 검증합니다. 값이 해당 타입의 제로 값이 아님을 보장하며 모든 타입에서 작동합니다.

Parameters / 매개변수:

  • None (operates on validator's value) 없음 (validator의 값에 대해 작동)

Returns / 반환:

  • *Validator: Returns self for method chaining 메서드 체이닝을 위해 자신을 반환

Behavior / 동작:

  • String: non-empty string 문자열: 비어있지 않은 문자열
  • Numbers: non-zero 숫자: 0이 아님
  • Boolean: true 불리언: true
  • Slice/Map: non-nil and length > 0 슬라이스/맵: nil이 아니고 길이 > 0
  • Pointer: non-nil 포인터: nil이 아님

Use Cases / 사용 사례:

  • Required field validation / 필수 필드 검증
  • Non-zero value check / 0이 아닌 값 확인
  • Initialized state verification / 초기화된 상태 확인
  • Generic required validation / 제네릭 필수 검증

Thread Safety / 스레드 안전성:

  • Thread-safe: No shared state / 스레드 안전: 공유 상태 없음

Performance / 성능:

  • Time complexity: O(1) for most types 시간 복잡도: 대부분 타입에서 O(1)
  • Reflection-based type switch 리플렉션 기반 타입 스위치

This validator checks if the value is not the zero value for its type. Similar to Required() but works for any type. 이 검증기는 값이 해당 타입의 제로 값이 아닌지 확인합니다. Required()와 유사하지만 모든 타입에 작동합니다.

Example / 예시:

// Valid non-empty string / 유효한 비어있지 않은 문자열
value := "hello"
v := validation.New(value, "required")
v.NotEmpty()  // Passes

// Valid non-zero number / 유효한 0이 아닌 숫자
v = validation.New(42, "count")
v.NotEmpty()  // Passes

// Valid true boolean / 유효한 true 불리언
v = validation.New(true, "flag")
v.NotEmpty()  // Passes

// Invalid - empty string / 무효 - 빈 문자열
v = validation.New("", "text")
v.NotEmpty()  // Fails

// Invalid - zero / 무효 - 제로
v = validation.New(0, "number")
v.NotEmpty()  // Fails

Validation rules / 검증 규칙:

  • Value must not be zero value for its type / 값이 해당 타입의 제로 값이 아니어야 함
Example

ExampleValidator_NotEmpty demonstrates non-empty value validation. ExampleValidator_NotEmpty는 비어있지 않은 값 검증을 보여줍니다.

package main

import (
	"fmt"

	"github.com/arkd0ng/go-utils/validation"
)

func main() {
	// Validate required field is not empty
	requiredField := "value"
	v := validation.New(requiredField, "required_field")
	v.NotEmpty()

	err := v.Validate()
	if err != nil {
		fmt.Println("Field must not be empty")
	} else {
		fmt.Println("Field has a value")
	}
}
Output:

Field has a value

func (*Validator) NotEquals

func (v *Validator) NotEquals(value interface{}) *Validator

NotEquals validates that the value is NOT equal to the given value. Uses Go's != operator for comparison, supporting all comparable types.

NotEquals는 값이 주어진 값과 같지 않은지 검증합니다. 비교 가능한 모든 타입을 지원하는 Go의 != 연산자를 사용합니다.

Parameters / 매개변수:

  • value: The forbidden value to compare against 비교할 금지 값

Returns / 반환:

  • *Validator: Returns self for method chaining 메서드 체이닝을 위해 자신을 반환

Behavior / 동작:

  • Uses != operator for comparison 비교에 != 연산자 사용
  • Type-sensitive comparison (5 != "5") 타입 구분 비교 (5 != "5")
  • Case-sensitive for strings 문자열은 대소문자 구분
  • Fails only on exact match 정확히 일치할 때만 실패

Use Cases / 사용 사례:

  • Prevent reusing old password / 이전 비밀번호 재사용 방지
  • Forbidden value validation / 금지된 값 검증
  • Ensure value has changed / 값이 변경되었는지 확인
  • Default value prevention / 기본값 방지
  • Duplicate prevention / 중복 방지

Thread Safety / 스레드 안전성:

  • Thread-safe: No shared state / 스레드 안전: 공유 상태 없음

Performance / 성능:

  • Time complexity: O(1) for primitive types 시간 복잡도: 기본 타입의 경우 O(1)
  • Direct comparison, very fast 직접 비교, 매우 빠름

Example / 예제:

// Prevent old password / 이전 비밀번호 방지
v := validation.New("newpassword123", "new_password")
v.NotEquals(oldPassword)  // Must be different

// Ensure value changed / 값 변경 확인
v := validation.New(newEmail, "email")
v.NotEquals(currentEmail)

// Forbidden value / 금지된 값
v := validation.New("guest", "username")
v.NotEquals("admin")  // Cannot be admin

// Default value prevention / 기본값 방지
v := validation.New(status, "status")
v.NotEquals("unknown")  // Must set a valid status

// Multiple forbidden values / 여러 금지 값
v := validation.New(role, "role")
v.NotEquals("root").NotEquals("system")
Example

ExampleValidator_NotEquals demonstrates the NotEquals validator ExampleValidator_NotEquals는 NotEquals 검증기를 보여줍니다

package main

import (
	"fmt"

	"github.com/arkd0ng/go-utils/validation"
)

func main() {
	v := validation.New("newpassword", "password")
	v.NotEquals("oldpassword")
	err := v.Validate()
	if err != nil {
		fmt.Println("Passwords must be different")
	} else {
		fmt.Println("Valid new password")
	}
}
Output:

Valid new password

func (*Validator) NotIn

func (v *Validator) NotIn(values ...interface{}) *Validator

NotIn validates that the value does NOT exist in the given list of forbidden values. Uses deep equality for comparison, supporting any comparable type.

NotIn은 값이 주어진 금지 값 목록에 존재하지 않는지 검증합니다. 깊은 동등성 비교를 사용하며 비교 가능한 모든 타입을 지원합니다.

Parameters / 매개변수:

  • values: Variadic list of forbidden values 금지된 값들의 가변 인자 목록

Returns / 반환:

  • *Validator: Returns self for method chaining 메서드 체이닝을 위해 자신을 반환

Behavior / 동작:

  • Uses reflect.DeepEqual for comparison reflect.DeepEqual을 사용하여 비교
  • Supports any type (strings, numbers, structs, etc.) 모든 타입 지원 (문자열, 숫자, 구조체 등)
  • Case-sensitive for strings 문자열은 대소문자 구분
  • Fails if value found in forbidden list 금지 목록에서 값을 찾으면 실패

Use Cases / 사용 사례:

  • Blacklist validation / 블랙리스트 검증
  • Reserved value prevention / 예약된 값 방지
  • Forbidden status/state validation / 금지된 상태/상태 검증
  • Role restriction / 역할 제한
  • Banned input prevention / 금지된 입력 방지

Thread Safety / 스레드 안전성:

  • Thread-safe: No shared state / 스레드 안전: 공유 상태 없음

Performance / 성능:

  • Time complexity: O(n) where n is number of forbidden values 시간 복잡도: O(n) (n은 금지 값의 수)
  • Linear search through values list 값 목록을 선형 검색
  • DeepEqual can be expensive for complex types DeepEqual은 복잡한 타입에서 비용이 클 수 있음

Example / 예제:

// Reserved usernames / 예약된 사용자명
v := validation.New("user123", "username")
v.NotIn("admin", "root", "system")  // Passes / 성공

v := validation.New("admin", "username")
v.NotIn("admin", "root", "system")  // Fails / 실패

// Role restriction / 역할 제한
v := validation.New("editor", "role")
v.NotIn("guest", "anonymous")  // Passes / 성공

// Forbidden status / 금지된 상태
v := validation.New(newStatus, "status")
v.Required().NotIn("deleted", "archived")

// Reserved words / 예약어
v := validation.New(tableName, "table_name")
v.NotIn("select", "delete", "drop", "insert")
Example

ExampleValidator_NotIn demonstrates the NotIn validator ExampleValidator_NotIn는 NotIn 검증기를 보여줍니다

package main

import (
	"fmt"

	"github.com/arkd0ng/go-utils/validation"
)

func main() {
	v := validation.New("admin", "role")
	v.NotIn("guest", "anonymous")
	err := v.Validate()
	if err != nil {
		fmt.Println("Forbidden role")
	} else {
		fmt.Println("Allowed role")
	}
}
Output:

Allowed role

func (*Validator) NotNil

func (v *Validator) NotNil() *Validator

NotNil validates that the value is not nil. Uses reflection to ensure pointers, interfaces, slices, maps, channels, and functions are not nil.

NotNil은 값이 nil이 아닌지 검증합니다. 리플렉션을 사용하여 포인터, 인터페이스, 슬라이스, 맵, 채널 및 함수가 nil이 아님을 보장합니다.

Parameters / 매개변수:

  • None (operates on validator's value) 없음 (validator의 값에 대해 작동)

Returns / 반환:

  • *Validator: Returns self for method chaining 메서드 체이닝을 위해 자신을 반환

Behavior / 동작:

  • Rejects nil value nil 값 거부
  • Checks non-nil pointers via reflection 리플렉션을 통한 nil이 아닌 포인터 확인
  • Supports: pointer, interface, slice, map, channel, func 지원: 포인터, 인터페이스, 슬라이스, 맵, 채널, 함수
  • Fails on nil values nil 값에 실패

Use Cases / 사용 사례:

  • Required pointer fields / 필수 포인터 필드
  • Non-null validation / non-null 검증
  • Reference existence check / 참조 존재 확인
  • Dependency validation / 의존성 검증

Thread Safety / 스레드 안전성:

  • Thread-safe: No shared state / 스레드 안전: 공유 상태 없음

Performance / 성능:

  • Time complexity: O(1) 시간 복잡도: O(1)
  • Reflection-based nil check 리플렉션 기반 nil 확인

This validator checks if the value is not nil (pointer, interface, slice, map, channel, func). Useful for validating required pointer fields. 이 검증기는 값이 nil이 아닌지 확인합니다 (포인터, 인터페이스, 슬라이스, 맵, 채널, 함수). 필수 포인터 필드를 검증하는 데 유용합니다.

Example / 예시:

// Valid - non-nil pointer / 유효 - nil이 아닌 포인터
str := "value"
ptr := &str
v := validation.New(ptr, "required_ptr")
v.NotNil()  // Passes

// Valid - initialized slice / 유효 - 초기화된 슬라이스
slice := []int{1, 2, 3}
v = validation.New(slice, "data")
v.NotNil()  // Passes

// Invalid - nil pointer / 무효 - nil 포인터
var nilPtr *string
v = validation.New(nilPtr, "ptr")
v.NotNil()  // Fails

// Invalid - nil slice / 무효 - nil 슬라이스
var nilSlice []int
v = validation.New(nilSlice, "data")
v.NotNil()  // Fails

Validation rules / 검증 규칙:

  • Value must not be nil / 값이 nil이 아니어야 함
  • Works with pointers, interfaces, slices, maps, channels, functions
Example

ExampleValidator_NotNil demonstrates non-nil value validation. ExampleValidator_NotNil는 non-nil 값 검증을 보여줍니다.

package main

import (
	"fmt"

	"github.com/arkd0ng/go-utils/validation"
)

func main() {
	// Validate required pointer is not nil
	value := "test"
	ptr := &value
	v := validation.New(ptr, "required_ptr")
	v.NotNil()

	err := v.Validate()
	if err != nil {
		fmt.Println("Pointer must not be nil")
	} else {
		fmt.Println("Pointer has a value")
	}
}
Output:

Pointer has a value

func (*Validator) NotOneOf

func (v *Validator) NotOneOf(values ...interface{}) *Validator

NotOneOf validates that the value does not match any of the provided values. Useful for blacklisting specific values and preventing reserved keywords.

NotOneOf는 값이 제공된 값 중 어느 것과도 일치하지 않는지 검증합니다. 특정 값을 블랙리스트에 추가하고 예약어를 방지하는 데 유용합니다.

Parameters / 매개변수:

  • values: Variadic list of forbidden values 가변 인자로 전달된 금지 값 목록

Returns / 반환:

  • *Validator: Returns self for method chaining 메서드 체이닝을 위해 자신을 반환

Behavior / 동작:

  • Uses == operator for comparison == 연산자를 사용하여 비교
  • Accepts any type (interface{}) 모든 타입 허용 (interface{})
  • At least one forbidden value required 최소 하나의 금지 값 필요
  • Passes if value differs from all provided values 값이 제공된 모든 값과 다르면 통과
  • Fails if any match found 일치하는 값이 있으면 실패

Use Cases / 사용 사례:

  • Reserved keyword prevention / 예약어 방지
  • Blacklisted value validation / 블랙리스트 값 검증
  • Username restriction / 사용자명 제한
  • Forbidden value checking / 금지 값 확인

Thread Safety / 스레드 안전성:

  • Thread-safe: No shared state / 스레드 안전: 공유 상태 없음

Performance / 성능:

  • Time complexity: O(n), n = number of forbidden values 시간 복잡도: O(n), n = 금지 값 개수
  • Linear search through forbidden values 금지 값을 통한 선형 검색

This validator checks if the value is different from all forbidden values. Useful for blacklisting specific values or preventing reserved keywords. 이 검증기는 값이 모든 금지된 값과 다른지 확인합니다. 특정 값을 블랙리스트에 추가하거나 예약어를 방지하는 데 유용합니다.

Example / 예시:

// Reserved username prevention / 예약된 사용자명 방지
username := "john"
v := validation.New(username, "username")
v.NotOneOf("admin", "root", "administrator")  // Passes

// Forbidden status / 금지된 상태
v = validation.New("active", "status")
v.NotOneOf("deleted", "banned", "suspended")  // Passes

// Numeric blacklist / 숫자 블랙리스트
v = validation.New(42, "port")
v.NotOneOf(0, 80, 443, 8080)  // Passes

// Invalid - forbidden value / 무효 - 금지 값
v = validation.New("admin", "username")
v.NotOneOf("admin", "root", "administrator")  // Fails

Validation rules / 검증 규칙:

  • Value must not equal any of the provided values / 값이 제공된 값 중 어느 것과도 같지 않아야 함
  • Comparison uses == operator / 비교는 == 연산자 사용
  • At least one forbidden value must be provided / 최소 하나의 금지 값이 제공되어야 함
Example

ExampleValidator_NotOneOf demonstrates NotOneOf validation. ExampleValidator_NotOneOf는 NotOneOf 검증을 보여줍니다.

package main

import (
	"fmt"

	"github.com/arkd0ng/go-utils/validation"
)

func main() {
	v := validation.New("user123", "username")
	v.NotOneOf("admin", "root", "administrator")

	err := v.Validate()
	if err != nil {
		fmt.Println("Forbidden username")
	} else {
		fmt.Println("Valid username")
	}
}
Output:

Valid username

func (*Validator) Numeric

func (v *Validator) Numeric() *Validator

Numeric validates that the string contains only numeric digits. Supports Unicode digits from all languages. Empty strings fail validation.

Numeric은 문자열이 숫자만 포함하는지 검증합니다. 모든 언어의 유니코드 숫자를 지원합니다. 빈 문자열은 검증 실패합니다.

Character Rules / 문자 규칙:

  • Only Unicode digits (Nd category) allowed 유니코드 숫자만 허용 (Nd 카테고리)
  • No letters, spaces, punctuation, or special characters 문자, 공백, 구두점, 특수 문자 불허
  • No decimal points or negative signs 소수점이나 음수 기호 불허
  • Empty string fails (unlike Alpha/Alphanumeric) 빈 문자열 실패 (Alpha/Alphanumeric과 다름)

Valid Examples / 유효한 예:

  • "123"
  • "0"
  • "١٢٣" (Arabic-Indic digits / 아랍-인도 숫자)
  • "१२३" (Devanagari digits / 데바나가리 숫자)

Invalid Examples / 유효하지 않은 예:

  • "" (empty string)
  • "12.34" (contains decimal)
  • "-123" (contains minus sign)
  • "123abc" (contains letters)
  • "1 2 3" (contains spaces)

Returns / 반환:

  • *Validator: Returns self for method chaining 메서드 체이닝을 위해 자신을 반환

Behavior / 동작:

  • Iterates through each rune 각 rune을 반복
  • Uses unicode.IsDigit() for validation unicode.IsDigit()를 사용하여 검증
  • Empty string explicitly fails (len check) 빈 문자열은 명시적으로 실패 (길이 검사)
  • Skips validation if value is not a string 값이 문자열이 아니면 검증 건너뜀

Use Cases / 사용 사례:

  • ID numbers / ID 번호
  • Numeric codes / 숫자 코드
  • PIN validation / PIN 검증
  • Integer-only input / 정수 전용 입력
  • Quantity fields / 수량 필드

Thread Safety / 스레드 안전성:

  • Thread-safe: No shared state / 스레드 안전: 공유 상태 없음

Performance / 성능:

  • Time complexity: O(n) where n is string length 시간 복잡도: O(n) (n은 문자열 길이)
  • Checks each rune individually 각 rune을 개별적으로 검사

Note / 참고:

  • For decimal numbers, use a different validator 소수를 위해서는 다른 검증기 사용
  • For negative numbers, use a different validator 음수를 위해서는 다른 검증기 사용
  • This is for digit-only strings, not numeric values 이것은 숫자 값이 아닌 숫자 전용 문자열용

Example / 예제:

v := validation.New("12345", "code")
v.Numeric()  // Passes / 성공

v := validation.New("123abc", "code")
v.Numeric()  // Fails / 실패

v := validation.New("", "code")
v.Numeric()  // Fails (empty) / 실패 (빈 문자열)

// PIN code validation / PIN 코드 검증
v := validation.New(pin, "pin")
v.Numeric().Length(6)

// Product code / 제품 코드
v := validation.New(code, "product_code")
v.Required().Numeric().MinLength(8).MaxLength(12)

func (*Validator) Odd

func (v *Validator) Odd() *Validator

Odd validates that the numeric value is an odd number (not divisible by 2). Converts to integer before checking, so decimal parts are truncated.

Odd는 숫자 값이 홀수(2로 나누어떨어지지 않음)인지 검증합니다. 검사 전 정수로 변환하므로 소수 부분은 버려집니다.

Returns / 반환:

  • *Validator: Returns self for method chaining 메서드 체이닝을 위해 자신을 반환

Behavior / 동작:

  • Converts value to int before checking 검사 전 int로 변환
  • Truncates decimal part (3.9 becomes 3) 소수 부분 버림 (3.9는 3이 됨)
  • Uses modulo operation: val % 2 != 0 나머지 연산 사용: val % 2 != 0
  • Zero is NOT odd (it's even) 0은 홀수가 아님 (짝수임)
  • Negative odd numbers are valid (-1, -3, etc.) 음수 홀수도 유효 (-1, -3 등)
  • Skips validation if value is not numeric 값이 숫자가 아니면 검증 건너뜀

Use Cases / 사용 사례:

  • Odd number requirements / 홀수 요구사항
  • Alternating patterns / 교대 패턴
  • Index validation (odd indices) 인덱스 검증 (홀수 인덱스)
  • Mathematical constraints / 수학적 제약

Thread Safety / 스레드 안전성:

  • Thread-safe: No shared state / 스레드 안전: 공유 상태 없음

Performance / 성능:

  • Time complexity: O(1) 시간 복잡도: O(1)
  • Single modulo operation 단일 나머지 연산

Important Note / 중요 참고:

  • Float values are truncated, not rounded 부동 소수점 값은 반올림이 아닌 버림
  • 3.1 becomes 3 (odd), not 4 (even) 3.1은 4(짝수)가 아닌 3(홀수)가 됨
  • For precise integer checking, use integer types 정확한 정수 검사를 위해 정수 타입 사용

Example / 예제:

v := validation.New(3, "value")
v.Odd()  // Passes / 성공

v := validation.New(4, "value")
v.Odd()  // Fails / 실패

v := validation.New(0, "value")
v.Odd()  // Fails (zero is even) / 실패 (0은 짝수)

v := validation.New(-3, "value")
v.Odd()  // Passes / 성공

v := validation.New(3.9, "value")
v.Odd()  // Passes (truncated to 3) / 성공 (3으로 버림)

// Page number validation / 페이지 번호 검증
v := validation.New(page, "page")
v.Positive().Odd()

func (*Validator) OneOf

func (v *Validator) OneOf(values ...interface{}) *Validator

OneOf validates that the value matches one of the provided values. Useful for enum-like validation and restricted choice fields.

OneOf는 값이 제공된 값 중 하나와 일치하는지 검증합니다. 열거형 검증 및 제한된 선택 필드에 유용합니다.

Parameters / 매개변수:

  • values: Variadic list of allowed values 가변 인자로 전달된 허용 값 목록

Returns / 반환:

  • *Validator: Returns self for method chaining 메서드 체이닝을 위해 자신을 반환

Behavior / 동작:

  • Uses == operator for comparison == 연산자를 사용하여 비교
  • Accepts any type (interface{}) 모든 타입 허용 (interface{})
  • At least one allowed value required 최소 하나의 허용 값 필요
  • Passes if value equals any provided value 값이 제공된 값 중 하나와 같으면 통과
  • Fails if no match found 일치하는 값이 없으면 실패

Use Cases / 사용 사례:

  • Status field validation / 상태 필드 검증
  • Enum-like fields / 열거형 필드
  • Restricted choice validation / 제한된 선택 검증
  • Role validation / 역할 검증

Thread Safety / 스레드 안전성:

  • Thread-safe: No shared state / 스레드 안전: 공유 상태 없음

Performance / 성능:

  • Time complexity: O(n), n = number of allowed values 시간 복잡도: O(n), n = 허용 값 개수
  • Linear search through allowed values 허용 값을 통한 선형 검색

This validator checks if the value equals any of the allowed values. Useful for validating enum-like fields or restricted choice fields. 이 검증기는 값이 허용된 값 중 하나와 같은지 확인합니다. 열거형 필드 또는 제한된 선택 필드를 검증하는 데 유용합니다.

Example / 예시:

// Status validation / 상태 검증
status := "active"
v := validation.New(status, "status")
v.OneOf("active", "inactive", "pending")  // Passes

// Role validation / 역할 검증
v = validation.New("admin", "role")
v.OneOf("admin", "user", "guest")  // Passes

// Numeric values / 숫자 값
v = validation.New(2, "priority")
v.OneOf(1, 2, 3, 4, 5)  // Passes

// Invalid value / 무효한 값
v = validation.New("banned", "status")
v.OneOf("active", "inactive", "pending")  // Fails

Validation rules / 검증 규칙:

  • Value must equal one of the provided values / 값이 제공된 값 중 하나와 같아야 함
  • Comparison uses == operator / 비교는 == 연산자 사용
  • At least one allowed value must be provided / 최소 하나의 허용 값이 제공되어야 함
Example

ExampleValidator_OneOf demonstrates OneOf validation. ExampleValidator_OneOf는 OneOf 검증을 보여줍니다.

package main

import (
	"fmt"

	"github.com/arkd0ng/go-utils/validation"
)

func main() {
	v := validation.New("active", "status")
	v.OneOf("active", "inactive", "pending")

	err := v.Validate()
	if err != nil {
		fmt.Println("Invalid status")
	} else {
		fmt.Println("Valid status")
	}
}
Output:

Valid status

func (*Validator) Phone

func (v *Validator) Phone() *Validator

Phone validates that the string is a valid phone number format. Supports international formats with various separators.

Phone은 문자열이 유효한 전화번호 형식인지 검증합니다. 다양한 구분자를 사용하는 국제 형식을 지원합니다.

Format Rules / 형식 규칙:

  • Minimum 10 digits after removing separators 구분자 제거 후 최소 10자리
  • Optional country code prefix (+) 선택적 국가 코드 접두사 (+)
  • Allowed separators: space, hyphen, parentheses, dot 허용되는 구분자: 공백, 하이픈, 괄호, 점
  • 1-4 digit groups separated by optional separators 선택적 구분자로 구분된 1-4자리 그룹

Valid Examples / 유효한 예:

  • "010-1234-5678" (Korean format)
  • "+82-10-1234-5678" (with country code)
  • "(02) 1234-5678" (with area code)
  • "1234567890" (no separators)
  • "+1-555-123-4567" (US format)
  • "02.1234.5678" (dot separators)

Invalid Examples / 유효하지 않은 예:

  • "123456789" (< 10 digits)
  • "abc-defg-hijk" (non-numeric)
  • "123 456" (< 10 digits after cleaning)
  • "" (empty)

Returns / 반환:

  • *Validator: Returns self for method chaining 메서드 체이닝을 위해 자신을 반환

Behavior / 동작:

  • Validates format using regex 정규식을 사용하여 형식 검증
  • Removes separators for digit count check 자릿수 확인을 위해 구분자 제거
  • Requires minimum 10 digits 최소 10자리 필요
  • Does not validate if number is active 번호가 활성 상태인지 검증하지 않음
  • Skips validation if value is not a string 값이 문자열이 아니면 검증 건너뜀

Use Cases / 사용 사례:

  • Contact information / 연락처 정보
  • User registration / 사용자 등록
  • Phone verification / 전화 인증
  • International phone numbers / 국제 전화번호

Thread Safety / 스레드 안전성:

  • Thread-safe: Regex compilation is safe 스레드 안전: 정규식 컴파일 안전

Performance / 성능:

  • Time complexity: O(n) where n is string length 시간 복잡도: O(n) (n은 문자열 길이)
  • Multiple string replacements for cleaning 정리를 위한 여러 문자열 교체
  • Regex compilation on each call 각 호출마다 정규식 컴파일

Limitations / 제한사항:

  • Simplified validation, may not match all formats 간소화된 검증, 모든 형식과 일치하지 않을 수 있음
  • Does not validate against country-specific rules 국가별 규칙에 대해 검증하지 않음
  • Does not verify if number actually exists 번호가 실제로 존재하는지 검증하지 않음

Example / 예제:

v := validation.New("010-1234-5678", "phone")
v.Phone()  // Passes / 성공

v := validation.New("+82-10-1234-5678", "phone")
v.Phone()  // Passes / 성공

v := validation.New("12345", "phone")
v.Phone()  // Fails (< 10 digits) / 실패 (10자리 미만)

// Korean mobile / 한국 휴대폰
v := validation.New(phone, "mobile")
v.Required().Phone().StartsWith("010")

// International phone / 국제 전화
v := validation.New(phone, "phone")
v.Required().Phone().StartsWith("+")

func (*Validator) Positive

func (v *Validator) Positive() *Validator

Positive validates that the numeric value is strictly greater than zero. Works with all numeric types: int, int8-64, uint, uint8-64, float32, float64.

Positive는 숫자 값이 0보다 엄격하게 큰지 검증합니다. 모든 숫자 타입에서 작동합니다: int, int8-64, uint, uint8-64, float32, float64.

Returns / 반환:

  • *Validator: Returns self for method chaining 메서드 체이닝을 위해 자신을 반환

Behavior / 동작:

  • Accepts value if val > 0 val > 0이면 허용
  • Zero is NOT valid (use NonZero for zero/positive) 0은 유효하지 않음 (0/양수는 NonZero 사용)
  • Converts value to float64 for comparison 비교를 위해 값을 float64로 변환
  • Skips validation if value is not numeric 값이 숫자가 아니면 검증 건너뜀

Use Cases / 사용 사례:

  • Price validation (must be > 0) 가격 검증 (0보다 커야 함)
  • Quantity validation / 수량 검증
  • Age validation / 나이 검증
  • Positive measurements / 양수 측정값
  • Count/frequency values / 횟수/빈도 값

Thread Safety / 스레드 안전성:

  • Thread-safe: No shared state / 스레드 안전: 공유 상태 없음

Performance / 성능:

  • Time complexity: O(1) 시간 복잡도: O(1)
  • Single numeric comparison 단일 숫자 비교

Example / 예제:

v := validation.New(10, "price")
v.Positive()  // Passes / 성공

v := validation.New(0, "price")
v.Positive()  // Fails (zero not positive) / 실패 (0은 양수 아님)

v := validation.New(-5, "price")
v.Positive()  // Fails / 실패

v := validation.New(0.01, "amount")
v.Positive()  // Passes / 성공

// Product price / 제품 가격
v := validation.New(price, "price")
v.Required().Positive().Max(999999.99)

// Quantity / 수량
v := validation.New(quantity, "quantity")
v.Positive().Min(1).Max(1000)

func (*Validator) Printable

func (v *Validator) Printable() *Validator

Printable validates that the value contains only printable ASCII characters (32-126). Excludes control characters, allowing only visible characters.

Printable은 값이 인쇄 가능한 ASCII 문자(32-126)만 포함하는지 검증합니다. 제어 문자를 제외하고 표시 가능한 문자만 허용합니다.

Parameters / 매개변수:

  • None (operates on validator's value) 없음 (validator의 값에 대해 작동)

Returns / 반환:

  • *Validator: Returns self for method chaining 메서드 체이닝을 위해 자신을 반환

Behavior / 동작:

  • Printable range: 32-126 인쇄 가능 범위: 32-126
  • Includes: letters, digits, punctuation, space 포함: 문자, 숫자, 구두점, 공백
  • Excludes: control characters (0-31, 127) 제외: 제어 문자 (0-31, 127)
  • Excludes: non-ASCII (>127) 제외: ASCII 이외 (>127)

Use Cases / 사용 사례:

  • Display text validation / 표시 텍스트 검증
  • User input sanitization / 사용자 입력 정제
  • Form field validation / 양식 필드 검증
  • Terminal-safe output / 터미널 안전 출력

Thread Safety / 스레드 안전성:

  • Thread-safe: No shared state / 스레드 안전: 공유 상태 없음

Performance / 성능:

  • Time complexity: O(n), n = string length 시간 복잡도: O(n), n = 문자열 길이
  • Single pass character check 단일 패스 문자 확인

Printable ASCII characters include letters, numbers, symbols, and space, but not control characters. 인쇄 가능한 ASCII 문자는 문자, 숫자, 기호, 공백을 포함하지만 제어 문자는 포함하지 않습니다.

Example / 예시:

// Valid printable / 유효한 인쇄 가능 문자
text := "Hello World! 123"
v := validation.New(text, "display_text")
v.Printable()  // Passes

// With symbols / 기호 포함
v = validation.New("Test@#$%123", "text")
v.Printable()  // Passes

// Invalid - contains newline / 무효 - 줄바꿈 포함
v = validation.New("Line1\nLine2", "text")
v.Printable()  // Fails (control char)

// Invalid - contains tab / 무효 - 탭 포함
v = validation.New("Col1\tCol2", "text")
v.Printable()  // Fails (control char)

Validation rules / 검증 규칙:

  • Must be a string / 문자열이어야 함
  • All characters must be printable ASCII (32-126) / 모든 문자가 인쇄 가능한 ASCII (32-126)
  • No control characters (0-31, 127) / 제어 문자 없음 (0-31, 127)
Example

ExampleValidator_Printable demonstrates printable ASCII character validation. ExampleValidator_Printable는 인쇄 가능한 ASCII 문자 검증을 보여줍니다.

package main

import (
	"fmt"

	"github.com/arkd0ng/go-utils/validation"
)

func main() {
	v := validation.New("Hello World! 123", "text")
	v.Printable()

	err := v.Validate()
	if err != nil {
		fmt.Println("Invalid printable")
	} else {
		fmt.Println("Valid printable")
	}
}
Output:

Valid printable

func (*Validator) RGB

func (v *Validator) RGB() *Validator

RGB validates that the value is a valid RGB color format. Format: rgb(r, g, b) where r, g, b are integers 0-255.

RGB는 값이 유효한 RGB 색상 형식인지 검증합니다. 형식: rgb(r, g, b) 여기서 r, g, b는 0-255 범위의 정수입니다.

Parameters / 매개변수:

  • None (operates on validator's value) 없음 (validator의 값에 대해 작동)

Returns / 반환:

  • *Validator: Returns self for method chaining 메서드 체이닝을 위해 자신을 반환

Behavior / 동작:

  • Validates rgb(r, g, b) format rgb(r, g, b) 형식 검증
  • Red component: 0-255 빨강 구성 요소: 0-255
  • Green component: 0-255 초록 구성 요소: 0-255
  • Blue component: 0-255 파랑 구성 요소: 0-255
  • Spaces around commas optional 쉼표 주변 공백 선택 사항
  • Fails if value is not string 값이 문자열이 아니면 실패

Use Cases / 사용 사례:

  • CSS rgb() color validation / CSS rgb() 색상 검증
  • Web styling / 웹 스타일링
  • Color picker values / 색상 선택기 값
  • Design tool output / 디자인 도구 출력

Thread Safety / 스레드 안전성:

  • Thread-safe: No shared state / 스레드 안전: 공유 상태 없음

Performance / 성능:

  • Time complexity: O(n), n = string length 시간 복잡도: O(n), n = 문자열 길이
  • Single regex match + 3 range checks 단일 정규식 매칭 + 3번의 범위 확인

Format: rgb(r, g, b) where r, g, b are integers 0-255. 형식: rgb(r, g, b) 여기서 r, g, b는 0-255 범위의 정수입니다.

Example / 예시:

// Valid RGB colors / 유효한 RGB 색상
color := "rgb(255, 87, 51)"
v := validation.New(color, "background_color")
v.RGB()  // Passes

// With extra spaces / 추가 공백 포함
v = validation.New("rgb( 255 , 87 , 51 )", "color")
v.RGB()  // Passes (spaces allowed)

// Black / 검정색
v = validation.New("rgb(0, 0, 0)", "color")
v.RGB()  // Passes

// White / 흰색
v = validation.New("rgb(255, 255, 255)", "color")
v.RGB()  // Passes

// Invalid values / 무효한 값
v = validation.New("rgb(256, 87, 51)", "color")
v.RGB()  // Fails (red > 255)

v = validation.New("rgb(255, 87)", "color")
v.RGB()  // Fails (missing blue)

v = validation.New("255, 87, 51", "color")
v.RGB()  // Fails (missing rgb() wrapper)

Validation rules / 검증 규칙:

  • Must be a string / 문자열이어야 함
  • Format: rgb(r, g, b) / 형식: rgb(r, g, b)
  • Each component must be 0-255 / 각 구성 요소는 0-255 범위
  • Spaces around commas are optional / 쉼표 주변 공백은 선택 사항
Example

ExampleValidator_RGB demonstrates RGB color validation ExampleValidator_RGB는 RGB 색상 검증을 보여줍니다

package main

import (
	"fmt"

	"github.com/arkd0ng/go-utils/validation"
)

func main() {
	color := "rgb(255, 87, 51)"
	v := validation.New(color, "background_color")
	v.RGB()

	if len(v.GetErrors()) > 0 {
		fmt.Println("Invalid RGB color")
	} else {
		fmt.Println("Valid RGB color")
	}
}
Output:

Valid RGB color

func (*Validator) RGBA

func (v *Validator) RGBA() *Validator

RGBA validates that the value is a valid RGBA color format. Format: rgba(r, g, b, a) where r, g, b are 0-255 integers and a is 0-1 float.

RGBA는 값이 유효한 RGBA 색상 형식인지 검증합니다. 형식: rgba(r, g, b, a) 여기서 r, g, b는 0-255 정수이고 a는 0-1 부동소수점입니다.

Parameters / 매개변수:

  • None (operates on validator's value) 없음 (validator의 값에 대해 작동)

Returns / 반환:

  • *Validator: Returns self for method chaining 메서드 체이닝을 위해 자신을 반환

Behavior / 동작:

  • Validates rgba(r, g, b, a) format rgba(r, g, b, a) 형식 검증
  • Red, Green, Blue: 0-255 (integers) 빨강, 초록, 파랑: 0-255 (정수)
  • Alpha: 0.0-1.0 (float, opacity) 알파: 0.0-1.0 (부동소수점, 불투명도)
  • Spaces around commas optional 쉼표 주변 공백 선택 사항
  • Fails if value is not string 값이 문자열이 아니면 실패

Use Cases / 사용 사례:

  • CSS rgba() color validation / CSS rgba() 색상 검증
  • Transparency effects / 투명도 효과
  • Overlay colors / 오버레이 색상
  • Semi-transparent UI elements / 반투명 UI 요소

Thread Safety / 스레드 안전성:

  • Thread-safe: No shared state / 스레드 안전: 공유 상태 없음

Performance / 성능:

  • Time complexity: O(n), n = string length 시간 복잡도: O(n), n = 문자열 길이
  • Single regex match + 4 range checks 단일 정규식 매칭 + 4번의 범위 확인

Format: rgba(r, g, b, a) where r, g, b are integers 0-255 and a is 0-1. 형식: rgba(r, g, b, a) 여기서 r, g, b는 0-255 정수이고 a는 0-1 범위입니다.

Example / 예시:

// Valid RGBA colors / 유효한 RGBA 색상
color := "rgba(255, 87, 51, 0.8)"
v := validation.New(color, "overlay_color")
v.RGBA()  // Passes (80% opaque)

// Fully opaque / 완전 불투명
v = validation.New("rgba(255, 87, 51, 1)", "color")
v.RGBA()  // Passes (alpha = 1.0)

// Fully transparent / 완전 투명
v = validation.New("rgba(255, 87, 51, 0)", "color")
v.RGBA()  // Passes (alpha = 0.0)

// Semi-transparent / 반투명
v = validation.New("rgba(0, 0, 0, 0.5)", "shadow")
v.RGBA()  // Passes (50% opacity)

// With spaces / 공백 포함
v = validation.New("rgba( 255 , 87 , 51 , 0.8 )", "color")
v.RGBA()  // Passes

// Invalid values / 무효한 값
v = validation.New("rgba(256, 87, 51, 0.8)", "color")
v.RGBA()  // Fails (red > 255)

v = validation.New("rgba(255, 87, 51, 1.5)", "color")
v.RGBA()  // Fails (alpha > 1.0)

v = validation.New("rgba(255, 87, 51)", "color")
v.RGBA()  // Fails (missing alpha)

Validation rules / 검증 규칙:

  • Must be a string / 문자열이어야 함
  • Format: rgba(r, g, b, a) / 형식: rgba(r, g, b, a)
  • RGB components must be 0-255 / RGB 구성 요소는 0-255 범위
  • Alpha must be 0-1 (0.0 to 1.0) / 알파는 0-1 범위 (0.0 ~ 1.0)
Example

ExampleValidator_RGBA demonstrates RGBA color validation ExampleValidator_RGBA는 RGBA 색상 검증을 보여줍니다

package main

import (
	"fmt"

	"github.com/arkd0ng/go-utils/validation"
)

func main() {
	color := "rgba(255, 87, 51, 0.8)"
	v := validation.New(color, "overlay_color")
	v.RGBA()

	if len(v.GetErrors()) > 0 {
		fmt.Println("Invalid RGBA color")
	} else {
		fmt.Println("Valid RGBA color")
	}
}
Output:

Valid RGBA color

func (*Validator) Regex

func (v *Validator) Regex(pattern string) *Validator

Regex validates that the string matches the given regular expression pattern. If the pattern is invalid, adds an error and returns without validation.

Regex는 문자열이 주어진 정규식 패턴과 일치하는지 검증합니다. 패턴이 유효하지 않으면 오류를 추가하고 검증 없이 반환합니다.

Parameters / 매개변수:

  • pattern: Regular expression pattern (Go regex syntax) 정규식 패턴 (Go 정규식 문법)

Returns / 반환:

  • *Validator: Returns self for method chaining 메서드 체이닝을 위해 자신을 반환

Behavior / 동작:

  • Compiles regex pattern on each call 각 호출마다 정규식 패턴 컴파일
  • Returns error if pattern is invalid 패턴이 유효하지 않으면 오류 반환
  • Uses Go's regexp package (RE2 syntax) Go의 regexp 패키지 사용 (RE2 문법)
  • Full string match not required (use ^$ for full match) 전체 문자열 매칭 불필요 (전체 매칭은 ^$ 사용)
  • Skips validation if value is not a string 값이 문자열이 아니면 검증 건너뜀

Use Cases / 사용 사례:

  • Custom format validation / 사용자 정의 형식 검증
  • Complex pattern matching / 복잡한 패턴 매칭
  • Business-specific rules / 비즈니스 특정 규칙
  • Advanced string validation / 고급 문자열 검증

Thread Safety / 스레드 안전성:

  • Thread-safe: Regex compilation is safe 스레드 안전: 정규식 컴파일 안전
  • Compiled regex is safe for concurrent use 컴파일된 정규식은 동시 사용 안전

Performance / 성능:

  • Time complexity: O(n) for typical patterns 시간 복잡도: 일반 패턴의 경우 O(n)
  • Regex compilation overhead on each call 각 호출마다 정규식 컴파일 오버헤드
  • Consider pre-compiled regex for frequent use 자주 사용하는 경우 사전 컴파일된 정규식 고려

Regex Syntax / 정규식 문법:

  • Go uses RE2 syntax (no backreferences) Go는 RE2 문법 사용 (역참조 없음)
  • Common patterns: ^, $, ., *, +, ?, [], (), | 일반 패턴: ^, $, ., *, +, ?, [], (), |
  • Character classes: \d, \w, \s 문자 클래스: \d, \w, \s

Example / 예제:

// Korean phone number / 한국 전화번호
v := validation.New("010-1234-5678", "phone")
v.Regex(`^010-\d{4}-\d{4}$`)  // Passes / 성공

// Alphanumeric with hyphens / 하이픈이 있는 영숫자
v := validation.New("ABC-123", "code")
v.Regex(`^[A-Z]+-\d+$`)  // Passes / 성공

// Invalid pattern / 유효하지 않은 패턴
v := validation.New("test", "value")
v.Regex(`[invalid(`)  // Error added / 오류 추가

// Partial match (no anchors) / 부분 매칭 (앵커 없음)
v := validation.New("abc123def", "value")
v.Regex(`\d+`)  // Passes (contains digits) / 성공 (숫자 포함)

// Full string match / 전체 문자열 매칭
v := validation.New("abc123", "value")
v.Regex(`^[a-z]+$`)  // Fails (has digits) / 실패 (숫자 있음)

func (*Validator) Required

func (v *Validator) Required() *Validator

Required validates that the value is not empty or whitespace-only. It trims whitespace before checking, so spaces alone will fail validation.

Required는 값이 비어있지 않거나 공백만 있지 않은지 검증합니다. 확인 전에 공백을 제거하므로 공백만 있으면 검증 실패합니다.

Behavior / 동작:

  • Trims leading and trailing whitespace 앞뒤 공백 제거
  • Fails if resulting string is empty 결과 문자열이 비어있으면 실패
  • Fails if value is not a string type 값이 문자열 타입이 아니면 실패

Use Cases / 사용 사례:

  • Form field validation / 폼 필드 검증
  • Required API parameters / 필수 API 매개변수
  • User input validation / 사용자 입력 검증

Thread Safety / 스레드 안전성:

  • Thread-safe: No shared state / 스레드 안전: 공유 상태 없음

Performance / 성능:

  • Time complexity: O(n) where n is string length 시간 복잡도: O(n) (n은 문자열 길이)

Example / 예제:

v := validation.New("", "name")
v.Required()  // Fails / 실패

v := validation.New("   ", "name")
v.Required()  // Fails (whitespace only) / 실패 (공백만)

v := validation.New("John", "name")
v.Required()  // Passes / 성공
Example

ExampleValidator_Required demonstrates the Required validator ExampleValidator_Required는 Required 검증기를 보여줍니다

package main

import (
	"fmt"

	"github.com/arkd0ng/go-utils/validation"
)

func main() {
	v := validation.New("", "username")
	v.Required()
	err := v.Validate()
	if err != nil {
		fmt.Println("Error: field is required")
	}
}
Output:

Error: field is required

func (*Validator) SHA1

func (v *Validator) SHA1() *Validator

SHA1 validates that the value is a valid SHA1 hash (40 hexadecimal characters). SHA1 produces 160-bit hash values typically represented as 40 hexadecimal digits.

SHA1은 값이 유효한 SHA1 해시(40자리 16진수)인지 검증합니다. SHA1은 일반적으로 40자리 16진수로 표현되는 160비트 해시 값을 생성합니다.

Parameters / 매개변수:

  • None (operates on validator's value) 없음 (validator의 값에 대해 작동)

Returns / 반환:

  • *Validator: Returns self for method chaining 메서드 체이닝을 위해 자신을 반환

Behavior / 동작:

  • Validates 40-character length 40자 길이 검증
  • Validates hexadecimal characters (0-9, a-f, A-F) 16진수 문자 검증 (0-9, a-f, A-F)
  • Case-insensitive 대소문자 구분 안 함
  • Does not validate hash correctness 해시 정확성 검증하지 않음

Use Cases / 사용 사례:

  • Git commit hash validation / Git 커밋 해시 검증
  • File integrity verification / 파일 무결성 확인
  • Digital signature validation / 디지털 서명 검증
  • Version control systems / 버전 관리 시스템

Thread Safety / 스레드 안전성:

  • Thread-safe: No shared state / 스레드 안전: 공유 상태 없음

Performance / 성능:

  • Time complexity: O(1), fixed length regex 시간 복잡도: O(1), 고정 길이 정규식
  • Simple pattern matching 간단한 패턴 매칭

Note: SHA1 is no longer considered cryptographically secure. Use SHA256 or stronger algorithms for security-critical applications.

참고: SHA1은 더 이상 암호학적으로 안전하지 않습니다. 보안이 중요한 애플리케이션에는 SHA256 이상의 강력한 알고리즘을 사용하세요.

Example / 예시:

// Valid SHA1 hash / 유효한 SHA1 해시
hash := "aaf4c61ddcc5e8a2dabede0f3b482cd9aea9434d"
v := validation.New(hash, "commit_hash")
v.SHA1()  // Passes

// Git commit hash / Git 커밋 해시
hash = "2fd4e1c67a2d28fced849ee1bb76e7391b93eb12"
v = validation.New(hash, "git_sha")
v.SHA1()  // Passes

// Invalid - wrong length / 무효 - 잘못된 길이
v = validation.New("aaf4c61ddcc5e8a2", "hash")
v.SHA1()  // Fails (too short)

// Invalid - non-hex characters / 무효 - 16진수가 아닌 문자
v = validation.New("zaf4c61ddcc5e8a2dabede0f3b482cd9aea9434d", "hash")
v.SHA1()  // Fails (contains 'z')

Validation rules / 검증 규칙:

  • Must be a string / 문자열이어야 함
  • Must be exactly 40 characters / 정확히 40자여야 함
  • Must contain only hexadecimal characters (0-9, a-f, A-F) / 16진수 문자만 포함

func (*Validator) SHA256

func (v *Validator) SHA256() *Validator

SHA256 validates that the value is a valid SHA256 hash (64 hexadecimal characters). SHA256 produces 256-bit hash values typically represented as 64 hexadecimal digits.

SHA256은 값이 유효한 SHA256 해시(64자리 16진수)인지 검증합니다. SHA256은 일반적으로 64자리 16진수로 표현되는 256비트 해시 값을 생성합니다.

Parameters / 매개변수:

  • None (operates on validator's value) 없음 (validator의 값에 대해 작동)

Returns / 반환:

  • *Validator: Returns self for method chaining 메서드 체이닝을 위해 자신을 반환

Behavior / 동작:

  • Validates 64-character length 64자 길이 검증
  • Validates hexadecimal characters (0-9, a-f, A-F) 16진수 문자 검증 (0-9, a-f, A-F)
  • Case-insensitive 대소문자 구분 안 함
  • Does not validate hash correctness 해시 정확성 검증하지 않음

Use Cases / 사용 사례:

  • File integrity verification / 파일 무결성 확인
  • Blockchain and cryptocurrency / 블록체인 및 암호화폐
  • Digital signatures / 디지털 서명
  • Password hashing (with salt) / 비밀번호 해싱 (솔트 포함)

Thread Safety / 스레드 안전성:

  • Thread-safe: No shared state / 스레드 안전: 공유 상태 없음

Performance / 성능:

  • Time complexity: O(1), fixed length regex 시간 복잡도: O(1), 고정 길이 정규식
  • Simple pattern matching 간단한 패턴 매칭

SHA256 is currently considered cryptographically secure and is widely used in security-critical applications.

SHA256은 현재 암호학적으로 안전한 것으로 간주되며 보안이 중요한 애플리케이션에서 널리 사용됩니다.

Example / 예시:

// Valid SHA256 hash / 유효한 SHA256 해시
hash := "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
v := validation.New(hash, "file_hash")
v.SHA256()  // Passes

// Bitcoin block hash / 비트코인 블록 해시
hash = "000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f"
v = validation.New(hash, "block_hash")
v.SHA256()  // Passes

// Invalid - wrong length / 무효 - 잘못된 길이
v = validation.New("e3b0c44298fc1c14", "hash")
v.SHA256()  // Fails (too short)

// Invalid - non-hex characters / 무효 - 16진수가 아닌 문자
v = validation.New("z3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", "hash")
v.SHA256()  // Fails (contains 'z')

Validation rules / 검증 규칙:

  • Must be a string / 문자열이어야 함
  • Must be exactly 64 characters / 정확히 64자여야 함
  • Must contain only hexadecimal characters (0-9, a-f, A-F) / 16진수 문자만 포함
Example

ExampleValidator_SHA256 demonstrates SHA256 hash validation ExampleValidator_SHA256는 SHA256 해시 검증을 보여줍니다

package main

import (
	"fmt"

	"github.com/arkd0ng/go-utils/validation"
)

func main() {
	hash := "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
	v := validation.New(hash, "file_hash")
	v.SHA256()

	if len(v.GetErrors()) > 0 {
		fmt.Println("Invalid SHA256")
	} else {
		fmt.Println("Valid SHA256")
	}
}
Output:

Valid SHA256

func (*Validator) SHA512

func (v *Validator) SHA512() *Validator

SHA512 validates that the value is a valid SHA512 hash (128 hexadecimal characters). SHA512 produces 512-bit hash values typically represented as 128 hexadecimal digits.

SHA512는 값이 유효한 SHA512 해시(128자리 16진수)인지 검증합니다. SHA512는 일반적으로 128자리 16진수로 표현되는 512비트 해시 값을 생성합니다.

Parameters / 매개변수:

  • None (operates on validator's value) 없음 (validator의 값에 대해 작동)

Returns / 반환:

  • *Validator: Returns self for method chaining 메서드 체이닝을 위해 자신을 반환

Behavior / 동작:

  • Validates 128-character length 128자 길이 검증
  • Validates hexadecimal characters (0-9, a-f, A-F) 16진수 문자 검증 (0-9, a-f, A-F)
  • Case-insensitive 대소문자 구분 안 함
  • Does not validate hash correctness 해시 정확성 검증하지 않음

Use Cases / 사용 사례:

  • High-security applications / 고보안 애플리케이션
  • Large file integrity / 대용량 파일 무결성
  • Certificate generation / 인증서 생성
  • Password hashing (with salt) / 비밀번호 해싱 (솔트 포함)

Thread Safety / 스레드 안전성:

  • Thread-safe: No shared state / 스레드 안전: 공유 상태 없음

Performance / 성능:

  • Time complexity: O(1), fixed length regex 시간 복잡도: O(1), 고정 길이 정규식
  • Simple pattern matching 간단한 패턴 매칭

SHA512 offers higher security than SHA256 but produces longer hash values. It is suitable for applications requiring maximum security.

SHA512는 SHA256보다 높은 보안성을 제공하지만 더 긴 해시 값을 생성합니다. 최대 보안이 필요한 애플리케이션에 적합합니다.

Example / 예시:

// Valid SHA512 hash / 유효한 SHA512 해시
hash := "cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e"
v := validation.New(hash, "password_hash")
v.SHA512()  // Passes

// File checksum / 파일 체크섬
hash = "ee26b0dd4af7e749aa1a8ee3c10ae9923f618980772e473f8819a5d4940e0db27ac185f8a0e1d5f84f88bc887fd67b143732c304cc5fa9ad8e6f57f50028a8ff"
v = validation.New(hash, "file_checksum")
v.SHA512()  // Passes

// Invalid - wrong length / 무효 - 잘못된 길이
v = validation.New("cf83e1357eefb8bdf1542850d66d8007", "hash")
v.SHA512()  // Fails (too short)

// Invalid - non-hex characters / 무효 - 16진수가 아닌 문자
v = validation.New("zf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e", "hash")
v.SHA512()  // Fails (contains 'z')

Validation rules / 검증 규칙:

  • Must be a string / 문자열이어야 함
  • Must be exactly 128 characters / 정확히 128자여야 함
  • Must contain only hexadecimal characters (0-9, a-f, A-F) / 16진수 문자만 포함

func (*Validator) StartsWith

func (v *Validator) StartsWith(prefix string) *Validator

StartsWith validates that the string starts with the given prefix. Case-sensitive comparison.

StartsWith는 문자열이 주어진 접두사로 시작하는지 검증합니다. 대소문자를 구분합니다.

Parameters / 매개변수:

  • prefix: The string that must appear at the beginning 시작 부분에 나타나야 하는 문자열

Returns / 반환:

  • *Validator: Returns self for method chaining 메서드 체이닝을 위해 자신을 반환

Behavior / 동작:

  • Case-sensitive comparison 대소문자 구분 비교
  • Uses strings.HasPrefix() internally 내부적으로 strings.HasPrefix() 사용
  • Empty prefix always passes 빈 접두사는 항상 통과
  • Skips validation if value is not a string 값이 문자열이 아니면 검증 건너뜀

Use Cases / 사용 사례:

  • URL scheme validation (http://, https://) URL 스킴 검증 (http://, https://)
  • File path validation (/, ./) 파일 경로 검증 (/, ./)
  • Code/ID prefix requirements (USER_, PROD_) 코드/ID 접두사 요구사항 (USER_, PROD_)
  • Command validation (/, !) 명령어 검증 (/, !)

Thread Safety / 스레드 안전성:

  • Thread-safe: No shared state / 스레드 안전: 공유 상태 없음

Performance / 성능:

  • Time complexity: O(n) where n is prefix length 시간 복잡도: O(n) (n은 접두사 길이)
  • Optimal performance for prefix checking 접두사 검사에 최적의 성능

Example / 예제:

v := validation.New("https://example.com", "url")
v.StartsWith("https://")  // Passes / 성공

v := validation.New("http://example.com", "url")
v.StartsWith("https://")  // Fails / 실패

v := validation.New("USER_12345", "user_id")
v.StartsWith("USER_")  // Passes / 성공

// Command prefix validation / 명령어 접두사 검증
v := validation.New(command, "command")
v.StartsWith("/").MinLength(2)

// Case sensitivity / 대소문자 구분
v := validation.New("Hello", "greeting")
v.StartsWith("hello")  // Fails (case mismatch) / 실패 (대소문자 불일치)

func (*Validator) StopOnError

func (v *Validator) StopOnError() *Validator

StopOnError sets the validator to stop on the first validation error. This is useful for expensive validations or when you only need to know if validation fails.

StopOnError는 첫 번째 검증 에러에서 멈추도록 검증기를 설정합니다. 비용이 많이 드는 검증이나 검증 실패 여부만 알면 될 때 유용합니다.

Returns / 반환값:

  • *Validator: The validator instance for method chaining 메서드 체이닝을 위한 검증기 인스턴스

Behavior / 동작:

  • Sets internal flag to stop after first error 첫 에러 후 중단하도록 내부 플래그 설정
  • All subsequent validation rules check this flag 모든 후속 검증 규칙이 이 플래그 확인
  • Does not affect already collected errors 이미 수집된 에러에는 영향 없음

Use Cases / 사용 사례:

  • Expensive validations (database lookups, API calls) 비용이 많이 드는 검증 (데이터베이스 조회, API 호출)
  • Early exit when any validation fails 검증 실패 시 조기 종료
  • Performance optimization for long validation chains 긴 검증 체인의 성능 최적화
  • When only boolean pass/fail is needed 통과/실패 여부만 필요할 때

Thread Safety / 스레드 안전성:

  • Thread-safe: Modifies validator state atomically 스레드 안전: 검증기 상태를 원자적으로 수정

Performance / 성능:

  • Time complexity: O(1) 시간 복잡도: O(1)
  • Can significantly reduce validation time for long chains 긴 체인의 경우 검증 시간을 크게 단축 가능
  • No memory allocation 메모리 할당 없음

Example / 예제:

// Basic usage / 기본 사용
v := validation.New(email, "email").StopOnError()
v.Required().Email().MaxLength(100)
// Stops at first failed rule / 첫 번째 실패한 규칙에서 중단

// With expensive validation / 비용이 많이 드는 검증과 함께
v := validation.New(username, "username").StopOnError()
v.Required().
  MinLength(3).         // Quick check first / 먼저 빠른 확인
  MaxLength(20).
  Custom(checkUsernameInDB)  // Expensive DB check last

// Compare with collect-all mode / 모든 에러 수집 모드와 비교
v1 := validation.New(data, "data").StopOnError()
// Stops at first error, faster / 첫 에러에서 중단, 더 빠름

v2 := validation.New(data, "data")
// Collects all errors, more informative / 모든 에러 수집, 더 많은 정보
Example

ExampleValidator_StopOnError demonstrates StopOnError behavior ExampleValidator_StopOnError는 StopOnError 동작을 보여줍니다

package main

import (
	"fmt"

	"github.com/arkd0ng/go-utils/validation"
)

func main() {
	v := validation.New("", "email")
	v.StopOnError()
	v.Required().Email().MinLength(5)
	err := v.Validate()
	if err != nil {
		verrs := err.(validation.ValidationErrors)
		fmt.Printf("Number of errors: %d\n", len(verrs))
	}
}
Output:

Number of errors: 1

func (*Validator) TimeFormat

func (v *Validator) TimeFormat(format string) *Validator

TimeFormat validates that the value is a valid time string in the specified format. Uses Go's time.Parse with the provided layout to verify time string validity.

TimeFormat은 값이 지정된 형식의 유효한 시간 문자열인지 검증합니다. 제공된 레이아웃으로 Go의 time.Parse를 사용하여 시간 문자열 유효성을 확인합니다.

Parameters / 매개변수:

  • format: Go time layout format string Go 시간 레이아웃 형식 문자열

Returns / 반환:

  • *Validator: Returns self for method chaining 메서드 체이닝을 위해 자신을 반환

Behavior / 동작:

  • Uses time.Parse for validation time.Parse를 사용하여 검증
  • Accepts any Go time layout format 모든 Go 시간 레이아웃 형식 허용
  • Common formats: 일반 형식:
  • "15:04:05" - 24-hour with seconds (HH:MM:SS)
  • "15:04" - 24-hour without seconds (HH:MM)
  • "03:04:05 PM" - 12-hour with seconds
  • "03:04 PM" - 12-hour without seconds
  • Fails if value is not string 값이 문자열이 아니면 실패
  • Fails if parsing fails 파싱 실패 시 실패

Use Cases / 사용 사례:

  • Time input validation / 시간 입력 검증
  • Form time field validation / 양식 시간 필드 검증
  • Schedule time validation / 일정 시간 검증
  • API time parameter validation / API 시간 매개변수 검증

Thread Safety / 스레드 안전성:

  • Thread-safe: No shared state / 스레드 안전: 공유 상태 없음

Performance / 성능:

  • Time complexity: O(n), n = string length 시간 복잡도: O(n), n = 문자열 길이
  • Single time.Parse call 단일 time.Parse 호출

Supported formats / 지원 형식:

  • "15:04:05" (HH:MM:SS)
  • "15:04" (HH:MM)
  • "03:04:05 PM" (12-hour with seconds)
  • "03:04 PM" (12-hour)
  • Any valid Go time.Parse format

Example / 예제:

// 24-hour format / 24시간 형식
v := validation.New("14:30:00", "meeting_time")
v.TimeFormat("15:04:05")  // Passes

// 24-hour without seconds / 초 없는 24시간 형식
v = validation.New("14:30", "time")
v.TimeFormat("15:04")  // Passes

// 12-hour format / 12시간 형식
v = validation.New("02:30 PM", "appointment")
v.TimeFormat("03:04 PM")  // Passes

// Invalid format / 무효한 형식
v = validation.New("14:30:00", "time")
v.TimeFormat("03:04 PM")  // Fails (format mismatch)

err := v.Validate()
Example

ExampleValidator_TimeFormat demonstrates time format validation ExampleValidator_TimeFormat는 시간 형식 검증을 보여줍니다

package main

import (
	"fmt"

	"github.com/arkd0ng/go-utils/validation"
)

func main() {
	v := validation.New("14:30:00", "meeting_time")
	v.TimeFormat("15:04:05")
	err := v.Validate()
	if err != nil {
		fmt.Println("Invalid time format")
	} else {
		fmt.Println("Valid time format")
	}
}
Output:

Valid time format

func (*Validator) True

func (v *Validator) True() *Validator

True validates that the value is boolean true. Requires exact boolean true value for strict validation.

True는 값이 불리언 true인지 검증합니다. 엄격한 검증을 위해 정확한 불리언 true 값이 필요합니다.

Parameters / 매개변수:

  • None (operates on validator's value) 없음 (validator의 값에 대해 작동)

Returns / 반환:

  • *Validator: Returns self for method chaining 메서드 체이닝을 위해 자신을 반환

Behavior / 동작:

  • Requires boolean type 불리언 타입 필요
  • Must be exactly true 정확히 true여야 함
  • Fails on false or non-boolean false 또는 불리언이 아니면 실패
  • No truthy conversion truthy 변환 없음

Use Cases / 사용 사례:

  • Checkbox acceptance / 체크박스 동의
  • Terms and conditions / 약관 동의
  • Feature flags / 기능 플래그
  • Permission grants / 권한 부여

Thread Safety / 스레드 안전성:

  • Thread-safe: No shared state / 스레드 안전: 공유 상태 없음

Performance / 성능:

  • Time complexity: O(1) 시간 복잡도: O(1)
  • Type assertion only 타입 단언만

This validator checks if the value is exactly boolean true. Useful for checkbox validation, terms acceptance, etc. 이 검증기는 값이 정확히 불리언 true인지 확인합니다. 체크박스 검증, 약관 동의 등에 유용합니다.

Example / 예시:

// Valid - true / 유효 - true
accepted := true
v := validation.New(accepted, "terms")
v.True()  // Passes

// Invalid - false / 무효 - false
v = validation.New(false, "terms")
v.True()  // Fails

// Invalid - not boolean / 무효 - 불리언 아님
v = validation.New(1, "value")
v.True()  // Fails (not bool type)

Validation rules / 검증 규칙:

  • Value must be boolean type / 값이 불리언 타입이어야 함
  • Value must be true / 값이 true여야 함
Example

ExampleValidator_True demonstrates boolean true validation. ExampleValidator_True는 불리언 true 검증을 보여줍니다.

package main

import (
	"fmt"

	"github.com/arkd0ng/go-utils/validation"
)

func main() {
	// Validate terms acceptance (must be true)
	accepted := true
	v := validation.New(accepted, "terms_accepted")
	v.True()

	err := v.Validate()
	if err != nil {
		fmt.Println("Terms must be accepted")
	} else {
		fmt.Println("Terms accepted")
	}
}
Output:

Terms accepted

func (*Validator) Type

func (v *Validator) Type(typeName string) *Validator

Type validates that the value is of the specified type. Uses reflection to compare runtime type with expected type name.

Type은 값이 지정된 타입인지 검증합니다. 리플렉션을 사용하여 런타임 타입과 예상 타입 이름을 비교합니다.

Parameters / 매개변수:

  • typeName: Expected type name (e.g., "string", "int", "slice") 예상 타입 이름 (예: "string", "int", "slice")

Returns / 반환:

  • *Validator: Returns self for method chaining 메서드 체이닝을 위해 자신을 반환

Behavior / 동작:

  • Uses reflect.Kind() for type checking 타입 확인에 reflect.Kind() 사용
  • Compares type name strings 타입 이름 문자열 비교
  • Fails on nil value nil 값에 실패
  • Case-sensitive type matching 대소문자 구분 타입 매칭

Use Cases / 사용 사례:

  • Dynamic type validation / 동적 타입 검증
  • Generic function validation / 제네릭 함수 검증
  • Interface type checking / 인터페이스 타입 확인
  • Runtime type enforcement / 런타임 타입 강제

Thread Safety / 스레드 안전성:

  • Thread-safe: No shared state / 스레드 안전: 공유 상태 없음

Performance / 성능:

  • Time complexity: O(1) 시간 복잡도: O(1)
  • Reflection type comparison 리플렉션 타입 비교

This validator checks if the value matches the specified type using reflection. Useful for dynamic type validation. 이 검증기는 리플렉션을 사용하여 값이 지정된 타입과 일치하는지 확인합니다. 동적 타입 검증에 유용합니다.

Example / 예시:

// Valid string type / 유효한 문자열 타입
value := "hello"
v := validation.New(value, "text")
v.Type("string")  // Passes

// Valid int type / 유효한 정수 타입
v = validation.New(42, "number")
v.Type("int")  // Passes

// Invalid type / 무효한 타입
v = validation.New("123", "number")
v.Type("int")  // Fails (is string)

// Nil value / Nil 값
v = validation.New(nil, "value")
v.Type("string")  // Fails (is nil)

Validation rules / 검증 규칙:

  • Value type must match specified type name / 값 타입이 지정된 타입 이름과 일치해야 함
  • Type names: "string", "int", "float64", "bool", "slice", "map", "struct", etc.
Example

ExampleValidator_Type demonstrates type validation. ExampleValidator_Type는 타입 검증을 보여줍니다.

package main

import (
	"fmt"

	"github.com/arkd0ng/go-utils/validation"
)

func main() {
	// Validate value is a string
	text := "hello"
	v := validation.New(text, "text")
	v.Type("string")

	err := v.Validate()
	if err != nil {
		fmt.Println("Must be a string")
	} else {
		fmt.Println("Correct type")
	}
}
Output:

Correct type

func (*Validator) URL

func (v *Validator) URL() *Validator

URL validates that the string is a valid URL format. Supports HTTP and HTTPS protocols only.

URL은 문자열이 유효한 URL 형식인지 검증합니다. HTTP 및 HTTPS 프로토콜만 지원합니다.

Format Rules / 형식 규칙:

  • Must start with http:// or https:// http:// 또는 https://로 시작해야 함
  • Must have valid domain/host 유효한 도메인/호스트 필요
  • May include path, query string, fragment 경로, 쿼리 문자열, 프래그먼트 포함 가능
  • No whitespace allowed 공백 허용 안 됨

Valid Examples / 유효한 예:

Invalid Examples / 유효하지 않은 예:

Returns / 반환:

  • *Validator: Returns self for method chaining 메서드 체이닝을 위해 자신을 반환

Behavior / 동작:

  • Validates format only, not actual URL accessibility 형식만 검증하며 실제 URL 접근성은 검증하지 않음
  • Case-sensitive for protocol (must be lowercase) 프로토콜은 대소문자 구분 (소문자여야 함)
  • Skips validation if value is not a string 값이 문자열이 아니면 검증 건너뜀

Use Cases / 사용 사례:

  • Website URL input / 웹사이트 URL 입력
  • API endpoint validation / API 엔드포인트 검증
  • Webhook URL / 웹훅 URL
  • External resource links / 외부 리소스 링크

Thread Safety / 스레드 안전성:

  • Thread-safe: Uses compiled regex (safe for concurrent use) 스레드 안전: 컴파일된 정규식 사용 (동시 사용 안전)

Performance / 성능:

  • Time complexity: O(n) where n is string length 시간 복잡도: O(n) (n은 문자열 길이)
  • Regex compilation happens on each call 각 호출마다 정규식 컴파일 발생

Limitations / 제한사항:

  • Only HTTP/HTTPS protocols supported HTTP/HTTPS 프로토콜만 지원
  • Does not validate if URL actually exists URL이 실제로 존재하는지 검증하지 않음
  • Simplified validation, may not catch all edge cases 간소화된 검증, 모든 엣지 케이스를 잡지 못할 수 있음

Example / 예제:

v := validation.New("https://example.com", "website")
v.URL()  // Passes / 성공

v := validation.New("not-a-url", "website")
v.URL()  // Fails / 실패

// API endpoint validation / API 엔드포인트 검증
v := validation.New(webhookURL, "webhook")
v.Required().URL().MaxLength(200)
Example

ExampleValidator_URL demonstrates the URL validator ExampleValidator_URL는 URL 검증기를 보여줍니다

package main

import (
	"fmt"

	"github.com/arkd0ng/go-utils/validation"
)

func main() {
	v := validation.New("https://example.com", "website")
	v.URL()
	err := v.Validate()
	if err != nil {
		fmt.Println("Invalid URL")
	} else {
		fmt.Println("Valid URL")
	}
}
Output:

Valid URL

func (*Validator) UUID

func (v *Validator) UUID() *Validator

UUID validates that the string is a valid UUID (Universally Unique Identifier). Supports standard UUID format (8-4-4-4-12 hexadecimal digits).

UUID는 문자열이 유효한 UUID(범용 고유 식별자)인지 검증합니다. 표준 UUID 형식 (8-4-4-4-12 16진수)을 지원합니다.

Format Rules / 형식 규칙:

  • Five groups of hexadecimal digits 5개 그룹의 16진수
  • Separated by hyphens: 8-4-4-4-12 하이픈으로 구분: 8-4-4-4-12
  • Total 36 characters (32 hex + 4 hyphens) 총 36자 (32 16진수 + 4 하이픈)
  • Case-insensitive (converted to lowercase) 대소문자 구분 없음 (소문자로 변환)

Valid Examples / 유효한 예:

  • "550e8400-e29b-41d4-a716-446655440000"
  • "6ba7b810-9dad-11d1-80b4-00c04fd430c8"
  • "550E8400-E29B-41D4-A716-446655440000" (uppercase)

Invalid Examples / 유효하지 않은 예:

  • "550e8400e29b41d4a716446655440000" (no hyphens)
  • "550e8400-e29b-41d4-a716" (incomplete)
  • "550e8400-e29b-41d4-a716-44665544000g" (invalid hex)
  • "550e8400-e29b-41d4-a716-4466554400000" (wrong length)

Returns / 반환:

  • *Validator: Returns self for method chaining 메서드 체이닝을 위해 자신을 반환

Behavior / 동작:

  • Converts to lowercase before validation 검증 전 소문자로 변환
  • Uses regex for format validation 형식 검증에 정규식 사용
  • Does not validate UUID version or variant UUID 버전이나 변형은 검증하지 않음
  • Skips validation if value is not a string 값이 문자열이 아니면 검증 건너뜀

Use Cases / 사용 사례:

  • Database primary keys / 데이터베이스 기본 키
  • Unique identifiers / 고유 식별자
  • Session IDs / 세션 ID
  • Resource identifiers in APIs / API의 리소스 식별자

Thread Safety / 스레드 안전성:

  • Thread-safe: Uses compiled regex (safe for concurrent use) 스레드 안전: 컴파일된 정규식 사용 (동시 사용 안전)

Performance / 성능:

  • Time complexity: O(n) where n is string length 시간 복잡도: O(n) (n은 문자열 길이)
  • String lowercase conversion overhead 문자열 소문자 변환 오버헤드

Limitations / 제한사항:

  • Does not distinguish UUID versions (v1, v4, etc.) UUID 버전 구분하지 않음 (v1, v4 등)
  • Does not validate timestamp in v1 UUIDs v1 UUID의 타임스탬프 검증하지 않음
  • Format validation only, not uniqueness 형식 검증만, 고유성은 검증하지 않음

Example / 예제:

v := validation.New("550e8400-e29b-41d4-a716-446655440000", "id")
v.UUID()  // Passes / 성공

v := validation.New("not-a-uuid", "id")
v.UUID()  // Fails / 실패

v := validation.New("550E8400-E29B-41D4-A716-446655440000", "id")
v.UUID()  // Passes (case insensitive) / 성공 (대소문자 구분 없음)

// API resource ID / API 리소스 ID
v := validation.New(resourceID, "resource_id")
v.Required().UUID()

func (*Validator) UUIDv4

func (v *Validator) UUIDv4() *Validator

UUIDv4 validates that the value is a valid UUID version 4. Specifically checks for UUID v4 format with correct version and variant bits.

UUIDv4는 값이 유효한 UUID 버전 4인지 검증합니다. 올바른 버전 및 변형 비트를 가진 UUID v4 형식을 구체적으로 확인합니다.

Parameters / 매개변수:

  • None (operates on validator's value) 없음 (validator의 값에 대해 작동)

Returns / 반환:

  • *Validator: Returns self for method chaining 메서드 체이닝을 위해 자신을 반환

Behavior / 동작:

  • Validates UUID v4 format (8-4-4-4-12 hex digits) UUID v4 형식 검증 (8-4-4-4-12 16진수)
  • Version field must be '4' (13th character after hyphens) 버전 필드는 '4'여야 함 (하이픈 이후 13번째 문자)
  • Variant field must be 8, 9, a, or b 변형 필드는 8, 9, a 또는 b여야 함
  • Case-insensitive hex validation 대소문자 구분 없는 16진수 검증
  • Fails if value is not string 값이 문자열이 아니면 실패

Use Cases / 사용 사례:

  • Unique identifier validation / 고유 식별자 검증
  • API key validation / API 키 검증
  • Resource ID validation / 리소스 ID 검증
  • Database key validation / 데이터베이스 키 검증

Thread Safety / 스레드 안전성:

  • Thread-safe: No shared state / 스레드 안전: 공유 상태 없음

Performance / 성능:

  • Time complexity: O(n), n = string length 시간 복잡도: O(n), n = 문자열 길이
  • Single regex match 단일 정규식 매칭

UUID v4 Format / UUID v4 형식:

  • Pattern: xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx
  • Version bit: '4' (13th position)
  • Variant bit: 8, 9, a, or b (17th position)

Example / 예제:

// Valid UUID v4 / 유효한 UUID v4
uuid := "550e8400-e29b-41d4-a716-446655440000"
v := validation.New(uuid, "user_id")
v.UUIDv4()  // Passes

// Lowercase / 소문자
v = validation.New("f47ac10b-58cc-4372-a567-0e02b2c3d479", "id")
v.UUIDv4()  // Passes

// Uppercase / 대문자
v = validation.New("F47AC10B-58CC-4372-A567-0E02B2C3D479", "id")
v.UUIDv4()  // Passes

// Invalid - wrong version / 무효 - 잘못된 버전
v = validation.New("550e8400-e29b-31d4-a716-446655440000", "id")
v.UUIDv4()  // Fails (version 3, not 4)

// Invalid - wrong variant / 무효 - 잘못된 변형
v = validation.New("550e8400-e29b-41d4-f716-446655440000", "id")
v.UUIDv4()  // Fails (variant f, not 8-b)

func (*Validator) Unless

func (v *Validator) Unless(predicate bool, fn func(*Validator)) *Validator

Unless executes the validation function only if the predicate returns false. Inverse of When - validates when condition is NOT met.

Unless는 조건이 거짓을 반환할 때만 검증 함수를 실행합니다. When의 반대 - 조건이 충족되지 않을 때 검증합니다.

Parameters / 매개변수:

  • predicate: Boolean condition determining if validation should be skipped 검증을 건너뛸지 결정하는 부울 조건
  • fn: Validation function to execute if predicate is false 조건이 거짓일 때 실행할 검증 함수

Returns / 반환:

  • *Validator: Returns self for method chaining 메서드 체이닝을 위해 자신을 반환

Behavior / 동작:

  • If predicate is false, executes fn(v) 조건이 거짓이면 fn(v) 실행
  • If predicate is true, skips validation 조건이 참이면 검증 건너뜀
  • Inverse logic of When validator When 검증기의 반대 논리
  • fn receives validator instance fn은 검증기 인스턴스를 받음
  • Supports nested validation chains 중첩된 검증 체인 지원

Use Cases / 사용 사례:

  • "Validate unless X" scenarios / "X가 아닌 경우 검증" 시나리오
  • Guest vs. registered user validation / 게스트 vs. 등록 사용자 검증
  • Optional field validation / 선택적 필드 검증
  • Exemption-based validation / 면제 기반 검증

Thread Safety / 스레드 안전성:

  • Thread-safe: No shared state / 스레드 안전: 공유 상태 없음

Performance / 성능:

  • Time complexity: O(1) + validation function cost 시간 복잡도: O(1) + 검증 함수 비용
  • Single predicate check 단일 조건 확인

This validator is the inverse of When - it executes validation when condition is false. Useful for "validate unless X" scenarios. 이 검증기는 When의 반대입니다 - 조건이 거짓일 때 검증을 실행합니다. "X가 아닌 경우 검증" 시나리오에 유용합니다.

Example / 예시:

// Email required unless guest / 게스트가 아닌 경우 이메일 필수
email := "user@example.com"
isGuest := false
v := validation.New(email, "email")
v.Unless(isGuest, func(val *Validator) {
    val.Required().Email()
})  // Passes (validated because not guest)

// Skip validation for admin / 관리자는 검증 건너뛰기
v = validation.New(username, "username")
v.Unless(isAdmin, func(val *Validator) {
    val.MinLength(5).MaxLength(20)
})

// Guest can skip email validation / 게스트는 이메일 검증 건너뛰기
v = validation.New("", "email")
v.Unless(true, func(val *Validator) {
    val.Required().Email()  // Not executed (predicate is true)
})  // Passes (validation skipped for guests)

// Validate unless premium user / 프리미엄 사용자가 아닌 경우 검증
isPremium := false
v = validation.New(uploadSize, "file_size")
v.Unless(isPremium, func(val *Validator) {
    val.Max(10485760)  // 10MB limit for non-premium
})

Validation rules / 검증 규칙:

  • If predicate is false, validation function is executed / 조건이 거짓이면 검증 함수 실행
  • If predicate is true, validation is skipped / 조건이 참이면 검증 건너뜀
  • Inverse of When validator / When 검증기의 반대
Example

ExampleValidator_Unless demonstrates conditional validation with Unless. ExampleValidator_Unless는 Unless를 사용한 조건부 검증을 보여줍니다.

package main

import (
	"fmt"

	"github.com/arkd0ng/go-utils/validation"
)

func main() {
	email := "user@example.com"
	isGuest := false

	v := validation.New(email, "email")
	v.Unless(isGuest, func(val *validation.Validator) {
		val.Required().Email()
	})

	err := v.Validate()
	if err != nil {
		fmt.Println("Invalid email")
	} else {
		fmt.Println("Valid email")
	}
}
Output:

Valid email

func (*Validator) Uppercase

func (v *Validator) Uppercase() *Validator

Uppercase validates that all letters in the string are uppercase. Non-letter characters are ignored.

Uppercase는 문자열의 모든 문자가 대문자인지 검증합니다. 문자가 아닌 문자는 무시됩니다.

Character Rules / 문자 규칙:

  • All letters must be uppercase 모든 문자는 대문자여야 함
  • Numbers and symbols are ignored 숫자와 기호는 무시됨
  • Empty string passes validation 빈 문자열은 검증 통과
  • Unicode uppercase letters supported 유니코드 대문자 지원

Valid Examples / 유효한 예:

  • "HELLO"
  • "HELLO123"
  • "HELLO-WORLD"
  • "안녕하세요" (no case distinction)
  • "123" (no letters)

Invalid Examples / 유효하지 않은 예:

  • "Hello" (has lowercase ello)
  • "hELLO" (has lowercase h)
  • "hello" (all lowercase)
  • "HeLLo123" (mixed case)

Returns / 반환:

  • *Validator: Returns self for method chaining 메서드 체이닝을 위해 자신을 반환

Behavior / 동작:

  • Compares string with its uppercase version 문자열을 대문자 버전과 비교
  • Uses strings.ToUpper() for comparison strings.ToUpper()를 사용하여 비교
  • Passes if string equals its uppercase form 문자열이 대문자 형태와 같으면 통과
  • Skips validation if value is not a string 값이 문자열이 아니면 검증 건너뜀

Use Cases / 사용 사례:

  • Country codes (ISO 3166) 국가 코드 (ISO 3166)
  • Currency codes (ISO 4217) 통화 코드 (ISO 4217)
  • Language codes (ISO 639) 언어 코드 (ISO 639)
  • Constant identifiers / 상수 식별자
  • Acronyms and abbreviations / 약어 및 약자

Thread Safety / 스레드 안전성:

  • Thread-safe: No shared state / 스레드 안전: 공유 상태 없음

Performance / 성능:

  • Time complexity: O(n) where n is string length 시간 복잡도: O(n) (n은 문자열 길이)
  • String allocation for uppercase conversion 대문자 변환을 위한 문자열 할당

Example / 예제:

v := validation.New("HELLO", "code")
v.Uppercase()  // Passes / 성공

v := validation.New("Hello", "code")
v.Uppercase()  // Fails / 실패

v := validation.New("HELLO123", "code")
v.Uppercase()  // Passes (numbers ignored) / 성공 (숫자 무시)

v := validation.New("USA", "country_code")
v.Uppercase()  // Passes / 성공

// Country code validation (ISO 3166) / 국가 코드 검증 (ISO 3166)
v := validation.New(countryCode, "country_code")
v.Required().Uppercase().Length(2).Alpha()

// Currency code (ISO 4217) / 통화 코드 (ISO 4217)
v := validation.New(currencyCode, "currency")
v.Required().Uppercase().Length(3).Alpha()

func (*Validator) Validate

func (v *Validator) Validate() error

Validate executes all validation rules and returns an error if any fail. It consolidates all collected validation errors into a single error type.

Validate는 모든 검증 규칙을 실행하고, 실패 시 에러를 반환합니다. 수집된 모든 검증 에러를 단일 에러 타입으로 통합합니다.

Returns / 반환값:

  • error: ValidationErrors containing all failed validations, or nil if all pass 모든 실패한 검증을 포함하는 ValidationErrors, 모두 통과 시 nil

Behavior / 동작:

  • Returns nil if no validation errors occurred 검증 에러가 없으면 nil 반환
  • Returns ValidationErrors type for type-safe error handling 타입 안전한 에러 처리를 위해 ValidationErrors 타입 반환
  • Does not clear error collection (can be called multiple times) 에러 컬렉션을 지우지 않음 (여러 번 호출 가능)

Error Handling / 에러 처리:

The returned error can be type-asserted to ValidationErrors for detailed inspection:
반환된 에러는 상세 검사를 위해 ValidationErrors로 타입 단언 가능:

if err := v.Validate(); err != nil {
    if validationErrors, ok := err.(validation.ValidationErrors); ok {
        for _, e := range validationErrors {
            // Process each error / 각 에러 처리
        }
    }
}

Thread Safety / 스레드 안전성:

  • Thread-safe: Read-only operation on validator state 스레드 안전: 검증기 상태에 대한 읽기 전용 작업

Performance / 성능:

  • Time complexity: O(1) 시간 복잡도: O(1)
  • No additional memory allocation 추가 메모리 할당 없음

Example / 예제:

v := validation.New(email, "email")
v.Required().Email()

if err := v.Validate(); err != nil {
    log.Printf("Validation failed: %v", err)
    return BadRequestError(err)
}

// Type-safe error handling / 타입 안전한 에러 처리
if err := v.Validate(); err != nil {
    errors := err.(validation.ValidationErrors)
    for _, e := range errors {
        fmt.Printf("Field '%s' failed rule '%s': %s\n",
            e.Field, e.Rule, e.Message)
    }
}

func (*Validator) When

func (v *Validator) When(predicate bool, fn func(*Validator)) *Validator

When executes the validation function only if the predicate returns true. Enables conditional validation based on runtime conditions.

When은 조건이 참을 반환할 때만 검증 함수를 실행합니다. 런타임 조건에 따른 조건부 검증을 활성화합니다.

Parameters / 매개변수:

  • predicate: Boolean condition determining if validation should run 검증 실행 여부를 결정하는 부울 조건
  • fn: Validation function to execute if predicate is true 조건이 참일 때 실행할 검증 함수

Returns / 반환:

  • *Validator: Returns self for method chaining 메서드 체이닝을 위해 자신을 반환

Behavior / 동작:

  • If predicate is true, executes fn(v) 조건이 참이면 fn(v) 실행
  • If predicate is false, skips validation 조건이 거짓이면 검증 건너뜀
  • fn receives validator instance fn은 검증기 인스턴스를 받음
  • Supports nested validation chains 중첩된 검증 체인 지원

Use Cases / 사용 사례:

  • Conditional field validation / 조건부 필드 검증
  • Role-based validation / 역할 기반 검증
  • Feature flag validation / 기능 플래그 검증
  • Dynamic validation rules / 동적 검증 규칙

Thread Safety / 스레드 안전성:

  • Thread-safe: No shared state / 스레드 안전: 공유 상태 없음

Performance / 성능:

  • Time complexity: O(1) + validation function cost 시간 복잡도: O(1) + 검증 함수 비용
  • Single predicate check 단일 조건 확인

This validator allows conditional validation based on runtime conditions. The validation function is only executed if the predicate evaluates to true. 이 검증기는 런타임 조건에 따라 조건부 검증을 허용합니다. 검증 함수는 조건이 참으로 평가될 때만 실행됩니다.

Example / 예시:

// Age-based validation / 나이 기반 검증
age := 25
isAdult := age >= 18
v := validation.New(age, "age")
v.When(isAdult, func(val *Validator) {
    val.Min(18).Max(120)
})  // Passes (validated because isAdult is true)

// Role-based email requirement / 역할 기반 이메일 필수
email := "user@example.com"
requireEmail := role == "registered"
v = validation.New(email, "email")
v.When(requireEmail, func(val *Validator) {
    val.Required().Email()
})

// Feature flag validation / 기능 플래그 검증
v = validation.New(value, "feature")
v.When(featureEnabled, func(val *Validator) {
    val.MinLength(10).MaxLength(100)
})

// Skipped validation / 건너뛴 검증
v = validation.New(10, "age")
v.When(false, func(val *Validator) {
    val.Min(18)  // Not executed (predicate is false)
})  // Passes (validation skipped)

Validation rules / 검증 규칙:

  • If predicate is true, validation function is executed / 조건이 참이면 검증 함수 실행
  • If predicate is false, validation is skipped / 조건이 거짓이면 검증 건너뜀
  • Useful for complex conditional validation logic / 복잡한 조건부 검증 로직에 유용
Example

ExampleValidator_When demonstrates conditional validation with When. ExampleValidator_When는 When을 사용한 조건부 검증을 보여줍니다.

package main

import (
	"fmt"

	"github.com/arkd0ng/go-utils/validation"
)

func main() {
	email := "user@example.com"
	isRequired := true

	v := validation.New(email, "email")
	v.When(isRequired, func(val *validation.Validator) {
		val.Required().Email()
	})

	err := v.Validate()
	if err != nil {
		fmt.Println("Invalid email")
	} else {
		fmt.Println("Valid email")
	}
}
Output:

Valid email

func (*Validator) Whitespace

func (v *Validator) Whitespace() *Validator

Whitespace validates that the value contains only whitespace characters. Uses unicode.IsSpace to check for all Unicode whitespace characters.

Whitespace는 값이 공백 문자만 포함하는지 검증합니다. unicode.IsSpace를 사용하여 모든 유니코드 공백 문자를 확인합니다.

Parameters / 매개변수:

  • None (operates on validator's value) 없음 (validator의 값에 대해 작동)

Returns / 반환:

  • *Validator: Returns self for method chaining 메서드 체이닝을 위해 자신을 반환

Behavior / 동작:

  • Must not be empty string 빈 문자열이면 안 됨
  • All characters must be whitespace 모든 문자가 공백이어야 함
  • Includes: space, tab, newline, carriage return 포함: 공백, 탭, 줄바꿈, 캐리지 리턴
  • Includes Unicode whitespace characters 유니코드 공백 문자 포함

Use Cases / 사용 사례:

  • Blank line detection / 빈 줄 감지
  • Formatting validation / 형식 검증
  • Padding verification / 패딩 확인
  • Template processing / 템플릿 처리

Thread Safety / 스레드 안전성:

  • Thread-safe: No shared state / 스레드 안전: 공유 상태 없음

Performance / 성능:

  • Time complexity: O(n), n = string length 시간 복잡도: O(n), n = 문자열 길이
  • Single pass Unicode check 단일 패스 유니코드 확인

This validator checks for space, tab, newline, and other Unicode whitespace characters. 이 검증기는 공백, 탭, 줄바꿈 및 기타 유니코드 공백 문자를 확인합니다.

Example / 예시:

// Valid whitespace / 유효한 공백
text := "   \t\n  "
v := validation.New(text, "whitespace_field")
v.Whitespace()  // Passes

// Only spaces / 공백만
v = validation.New("     ", "padding")
v.Whitespace()  // Passes

// Only tabs / 탭만
v = validation.New("\t\t\t", "indent")
v.Whitespace()  // Passes

// Invalid - contains text / 무효 - 텍스트 포함
v = validation.New("  hello  ", "text")
v.Whitespace()  // Fails

// Invalid - empty string / 무효 - 빈 문자열
v = validation.New("", "empty")
v.Whitespace()  // Fails

Validation rules / 검증 규칙:

  • Must be a string / 문자열이어야 함
  • All characters must be whitespace / 모든 문자가 공백이어야 함
  • String must not be empty / 문자열이 비어있지 않아야 함
Example

ExampleValidator_Whitespace demonstrates whitespace-only validation. ExampleValidator_Whitespace는 공백 문자만 있는지 검증을 보여줍니다.

package main

import (
	"fmt"

	"github.com/arkd0ng/go-utils/validation"
)

func main() {
	v := validation.New(" \t\n  ", "text")
	v.Whitespace()

	err := v.Validate()
	if err != nil {
		fmt.Println("Not whitespace")
	} else {
		fmt.Println("Valid whitespace")
	}
}
Output:

Valid whitespace

func (*Validator) WithCustomMessage

func (v *Validator) WithCustomMessage(rule, message string) *Validator

WithCustomMessage sets a custom message for a specific validation rule before it runs. WithCustomMessage는 검증 규칙이 실행되기 전에 특정 규칙에 대한 커스텀 메시지를 설정합니다.

This allows you to set custom messages upfront, unlike WithMessage() which modifies the last error. WithMessage()는 마지막 에러를 수정하는 것과 달리, 이 메서드는 미리 커스텀 메시지를 설정할 수 있습니다.

Example / 예시:

v := validation.New("", "email")
v.WithCustomMessage("required", "이메일을 입력해주세요")
v.WithCustomMessage("email", "올바른 이메일 형식이 아닙니다")
v.Required().Email()
Example

ExampleValidator_WithCustomMessage demonstrates setting a single custom error message. ExampleValidator_WithCustomMessage는 단일 커스텀 에러 메시지 설정을 보여줍니다.

package main

import (
	"fmt"

	"github.com/arkd0ng/go-utils/validation"
)

func main() {
	v := validation.New("", "email")
	v.WithCustomMessage("required", "Please enter your email address")
	v.Required()

	err := v.Validate()
	if err != nil {
		fmt.Println(err.Error())
	}
}
Output:

Please enter your email address

func (*Validator) WithCustomMessages

func (v *Validator) WithCustomMessages(messages map[string]string) *Validator

WithCustomMessages sets multiple custom messages for validation rules. WithCustomMessages는 검증 규칙에 대한 여러 커스텀 메시지를 설정합니다.

Example / 예시:

v := validation.New("", "password")
v.WithCustomMessages(map[string]string{
    "required":   "비밀번호를 입력해주세요",
    "min_length": "비밀번호는 8자 이상이어야 합니다",
    "max_length": "비밀번호는 20자 이하여야 합니다",
})
v.Required().MinLength(8).MaxLength(20)
Example

ExampleValidator_WithCustomMessages demonstrates setting multiple custom error messages. ExampleValidator_WithCustomMessages는 여러 커스텀 에러 메시지 설정을 보여줍니다.

package main

import (
	"fmt"

	"github.com/arkd0ng/go-utils/validation"
)

func main() {
	v := validation.New("ab", "password")
	v.WithCustomMessages(map[string]string{
		"required":  "비밀번호를 입력해주세요",
		"minlength": "비밀번호는 8자 이상이어야 합니다",
		"maxlength": "비밀번호는 20자 이하여야 합니다",
	})
	v.Required().MinLength(8).MaxLength(20)

	err := v.Validate()
	if err != nil {
		errors := v.GetErrors()
		fmt.Println(errors[0].Message)
	}
}
Output:

비밀번호는 8자 이상이어야 합니다
Example (MultiValidator)

ExampleValidator_WithCustomMessages_multiValidator demonstrates custom messages with MultiValidator. ExampleValidator_WithCustomMessages_multiValidator는 MultiValidator에서 커스텀 메시지를 보여줍니다.

package main

import (
	"fmt"

	"github.com/arkd0ng/go-utils/validation"
)

func main() {
	mv := validation.NewValidator()

	mv.Field("", "email").WithCustomMessages(map[string]string{
		"required": "Email is required",
		"email":    "Invalid email format",
	}).Required()

	mv.Field("short", "password").WithCustomMessages(map[string]string{
		"required":  "Password is required",
		"minlength": "Password must be at least 8 characters",
	}).Required().MinLength(8)

	err := mv.Validate()
	if err != nil {
		errors := mv.GetErrors()
		for _, e := range errors {
			fmt.Printf("%s: %s\n", e.Field, e.Message)
		}
	}
}
Output:

email: Email is required
password: Password must be at least 8 characters

func (*Validator) WithMessage

func (v *Validator) WithMessage(message string) *Validator

WithMessage sets a custom message for the last validation rule. WithMessage는 마지막 검증 규칙에 대한 사용자 정의 메시지를 설정합니다.

func (*Validator) XML

func (v *Validator) XML() *Validator

XML validates that the value is a valid XML string. Uses Go's xml.Unmarshal to verify XML structure validity.

XML은 값이 유효한 XML 문자열인지 검증합니다. Go의 xml.Unmarshal을 사용하여 XML 구조 유효성을 확인합니다.

Parameters / 매개변수:

  • None (operates on validator's value) 없음 (validator의 값에 대해 작동)

Returns / 반환:

  • *Validator: Returns self for method chaining 메서드 체이닝을 위해 자신을 반환

Behavior / 동작:

  • Trims whitespace before validation 검증 전 공백 제거
  • Uses xml.Unmarshal for parsing xml.Unmarshal을 사용하여 파싱
  • Validates XML structure and syntax XML 구조 및 구문 검증
  • Checks well-formedness 올바른 형식 확인
  • Fails if value is not string 값이 문자열이 아니면 실패

Use Cases / 사용 사례:

  • XML configuration validation / XML 구성 검증
  • SOAP message validation / SOAP 메시지 검증
  • XML data input validation / XML 데이터 입력 검증
  • API request/response validation / API 요청/응답 검증

Thread Safety / 스레드 안전성:

  • Thread-safe: No shared state / 스레드 안전: 공유 상태 없음

Performance / 성능:

  • Time complexity: O(n), n = XML length 시간 복잡도: O(n), n = XML 길이
  • Full XML parsing required 전체 XML 파싱 필요

Example / 예제:

// Valid XML / 유효한 XML
xmlStr := "<root><item>value</item></root>"
v := validation.New(xmlStr, "xml_data")
v.XML()  // Passes

// With attributes / 속성 포함
v = validation.New(`<root id="1"><item>value</item></root>`, "data")
v.XML()  // Passes

// With whitespace / 공백 포함
v = validation.New("  <root>text</root>  ", "xml")
v.XML()  // Passes (whitespace trimmed)

// Self-closing tag / 자체 닫기 태그
v = validation.New("<element />", "element")
v.XML()  // Passes

// Invalid - unclosed tag / 무효 - 닫히지 않은 태그
v = validation.New("<root><item>value</root>", "xml")
v.XML()  // Fails (mismatched tags)

// Invalid - not XML / 무효 - XML 아님
v = validation.New("plain text", "xml")
v.XML()  // Fails

func (*Validator) Zero

func (v *Validator) Zero() *Validator

Zero validates that the numeric value is exactly equal to zero. Works with all numeric types: int, int8-64, uint, uint8-64, float32, float64.

Zero는 숫자 값이 정확히 0과 같은지 검증합니다. 모든 숫자 타입에서 작동합니다: int, int8-64, uint, uint8-64, float32, float64.

Returns / 반환:

  • *Validator: Returns self for method chaining 메서드 체이닝을 위해 자신을 반환

Behavior / 동작:

  • Accepts value if val == 0 val == 0이면 허용
  • Exact equality comparison 정확한 동등 비교
  • Converts value to float64 for comparison 비교를 위해 값을 float64로 변환
  • Skips validation if value is not numeric 값이 숫자가 아니면 검증 건너뜀

Use Cases / 사용 사례:

  • Initial state validation / 초기 상태 검증
  • Reset value verification / 초기화 값 확인
  • Default value checking / 기본값 확인
  • Zero balance verification / 잔액 0 확인
  • Counter reset validation / 카운터 초기화 검증

Thread Safety / 스레드 안전성:

  • Thread-safe: No shared state / 스레드 안전: 공유 상태 없음

Performance / 성능:

  • Time complexity: O(1) 시간 복잡도: O(1)
  • Single numeric comparison 단일 숫자 비교

Floating Point Considerations / 부동 소수점 고려사항:

  • Direct equality check, no epsilon tolerance 직접 동등 검사, 엡실론 허용 없음
  • May have precision issues with float operations 부동 소수점 연산에서 정밀도 문제 발생 가능
  • For floating point, consider Between(-0.0001, 0.0001) 부동 소수점의 경우 Between(-0.0001, 0.0001) 고려

Example / 예제:

v := validation.New(0, "counter")
v.Zero()  // Passes / 성공

v := validation.New(1, "counter")
v.Zero()  // Fails / 실패

v := validation.New(-1, "counter")
v.Zero()  // Fails / 실패

v := validation.New(0.0, "balance")
v.Zero()  // Passes / 성공

// Balance verification / 잔액 확인
v := validation.New(balance, "balance")
v.Zero() // Must be settled

// Counter reset / 카운터 초기화
v := validation.New(counter, "counter")
v.Zero() // Must be reset

Jump to

Keyboard shortcuts

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