Skip to content
เข้าสู่ระบบ

Validation

การ validate input data ใน Go applications

package main
import (
"errors"
"fmt"
"regexp"
"strings"
)
type User struct {
Name string
Email string
Age int
Password string
}
func (u *User) Validate() error {
if strings.TrimSpace(u.Name) == "" {
return errors.New("name is required")
}
if len(u.Name) < 2 || len(u.Name) > 50 {
return errors.New("name must be 2-50 characters")
}
if !isValidEmail(u.Email) {
return errors.New("invalid email format")
}
if u.Age < 0 || u.Age > 150 {
return errors.New("age must be 0-150")
}
if len(u.Password) < 8 {
return errors.New("password must be at least 8 characters")
}
return nil
}
func isValidEmail(email string) bool {
pattern := `^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$`
matched, _ := regexp.MatchString(pattern, email)
return matched
}
func main() {
user := User{
Name: "Alice",
Email: "alice@example.com",
Age: 30,
Password: "password123",
}
if err := user.Validate(); err != nil {
fmt.Println("Validation error:", err)
return
}
fmt.Println("User is valid")
}

เข้าสู่ระบบเพื่อดูเนื้อหาเต็ม

ยืนยันตัวตนด้วยบัญชี Google เพื่อปลดล็อกบทความทั้งหมด