基于Beego Validation包实现嵌套JSON创建请求的校验
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 (likeCityForm) and each element in slices (likeReferrals), so you don't need extra code to loop through referrals. - Strict Rules: We added rules like
MinSizeto prevent empty/short names,Min(1)for city IDs, and a regexMatchrule 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

