You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于Beego Validation包实现嵌套JSON创建请求的校验

How to Validate Nested JSON for User Profiles with Beego Validation

Hey there! Let's work through getting full validation set up for your nested JSON user profile request using Beego's Validation package. First, let's recap the JSON payload we're working with:

{ 
  "firstname": "sathish", 
  "lastname": "kumar", 
  "city": { 
    "id": 12, 
    "name": "coimbatore" 
  }, 
  "referrals": [ 
    { "name": "vignesh", "mobile": "1234567890" }, 
    { "name": "melvin", "mobile": "1234567890" } 
  ] 
}

You already have a partial struct defined, so we'll expand that to cover the full JSON structure and add appropriate validation rules:

Step 1: Complete the Struct Definitions

Instead of using an anonymous struct for City, we'll define separate structs for nested objects to keep code clean and reusable. We'll also add stricter validation rules beyond just Required:

type ProfileForm struct {
    Firstname string       `json:"firstname" valid:"Required;MinSize(2)"` // Ensure name isn't too short
    Lastname  string       `json:"lastname" valid:"Required;MinSize(2)"`
    City      CityForm     `json:"city" valid:"Required"` // Validate nested City struct
    Referrals []ReferralForm `json:"referrals" valid:"Required;MinSize(1)"` // Ensure at least one referral
}

type CityForm struct {
    ID   int    `json:"id" valid:"Required;Min(1)"` // City ID should be a positive integer
    Name string `json:"name" valid:"Required;MinSize(3)"` // City name can't be too short
}

type ReferralForm struct {
    Name   string `json:"name" valid:"Required;MinSize(2)"`
    Mobile string `json:"mobile" valid:"Required;Match(/^[0-9]{10}$/)"` // Validate 10-digit mobile number
}

Step 2: Implement the Validation Logic

Beego's Validation package automatically handles recursive validation for nested structs and slices, so we don't need to manually loop through referrals. Here's how to use it in your controller:

import (
    "github.com/astaxie/beego/validation"
    "github.com/astaxie/beego/logs"
)

// Example controller method to handle profile creation
func (c *ProfileController) PostCreate() {
    var form ProfileForm

    // Bind incoming JSON to the struct
    if err := c.ParseForm(&form); err != nil {
        c.Data["json"] = map[string]string{"error": "Failed to parse request data"}
        c.ServeJSON()
        return
    }

    // Initialize validator
    valid := validation.Validation{}
    // Run validation on the entire struct
    isValid, err := valid.Valid(&form)

    if err != nil {
        // Handle unexpected validation errors (e.g., regex compilation issues)
        logs.Error("Validation process failed: ", err)
        c.Data["json"] = map[string]string{"error": "Internal validation error"}
        c.ServeJSON()
        return
    }

    if !isValid {
        // Collect all validation failure messages
        var errorMessages []string
        for _, validationErr := range valid.Errors {
            // The Key field will include nested paths like "City.Name" or "Referrals.0.Mobile"
            errorMessages = append(errorMessages, validationErr.Key+": "+validationErr.Message)
        }
        c.Data["json"] = map[string]interface{}{
            "valid":  false,
            "errors": errorMessages,
        }
        c.ServeJSON()
        return
    }

    // Validation passed - proceed with profile creation logic
    c.Data["json"] = map[string]string{"status": "success", "message": "User profile created successfully"}
    c.ServeJSON()
}

Key Notes:

  • Recursive Validation: Beego's Valid() method automatically validates nested structs (like CityForm) and each element in slices (like Referrals), so you don't need extra code to loop through referrals.
  • Strict Rules: We added rules like MinSize to prevent empty/short names, Min(1) for city IDs, and a regex Match rule to ensure mobile numbers are 10 digits.
  • Error Context: The validation errors include the full field path (e.g., Referrals.0.Mobile), making it easy for frontends to identify exactly which field failed.

内容的提问来源于stack exchange,提问作者Sathishkumar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 10:28:53