2

go version:1.18

request params

{
    "questions_batch_id": "1",
    "answer_list": [
        {
            "questions_ids": "1",
            "answer": [
                "2222","3333"
            ]
        }
    ]
}

validate code:

type Answer struct {
    QuestionsID string   `json:"questions_id" binding:"required"`
    Answer      []string `json:"answer" binding:"required"`
}

type AnswerQuestionParams struct {
    QuestionBatchId string    `json:"questions_batch_id" binding:"required"`
    AnswerList      []*Answer `json:"answer_list" binding:"required"`
    UserId          string    `json:"user_id" binding:"-"`
    UserType        string    `json:"user_type" binding:"-"`
}

I was used required,dive got an error :reflect: call of reflect.Value.Interface on zero Value

I hope when the questions_id in the answer_list does not exist, the verification fails

1 Answers1

1

dear friend to achieve the desired validation, you can create a custom validation function that checks if the QuestionsID exists in the answer list. Here's an example of how you can modify your code to perform this validation:

import (
    "github.com/go-playground/validator/v10"
)

type Answer struct {
    QuestionsID string   `json:"questions_id" binding:"required"`
    Answer      []string `json:"answer" binding:"required"`
}

type AnswerQuestionParams struct {
    QuestionBatchId string    `json:"questions_batch_id" binding:"required"`
    AnswerList      []*Answer `json:"answer_list" binding:"required,dive,customValidAnswerList"`
    UserId          string    `json:"user_id" binding:"-"`
    UserType        string    `json:"user_type" binding:"-"`
}

func validateAnswerList(fl validator.FieldLevel) bool {
    answerList := fl.Field().Interface().([]*Answer)
    questionsIDs := make(map[string]bool)
    
    for _, answer := range answerList {
        if _, exists := questionsIDs[answer.QuestionsID]; exists {
            return false
        }
        questionsIDs[answer.QuestionsID] = true
    }
    
    return true
}

func main() {
    if v, ok := binding.Validator.Engine().(*validator.Validate); ok {
        _ = v.RegisterValidation("customValidAnswerList", validateAnswerList)
    }
    
    // Your code here
}

In the example code above, the validateAnswerList function is a custom validation function that checks if there are any duplicate QuestionsID in the answer_list. If a duplicate is found, the validation fails. This function is registered as a custom validation customValidAnswerList using the RegisterValidation method.

With this modification, if the questions_id in the answer_list is duplicated, the validation will fail and an error will be returned.

hadirezaei
  • 152
  • 5