Home  >  Article  >  Backend Development  >  How to add validator tag to nested field

How to add validator tag to nested field

WBOY
WBOYforward
2024-02-09 10:10:171125browse

How to add validator tag to nested field

php Xiaobian Yuzai will introduce you how to add validator tags to nested fields in this article. During the development process, we often need to verify form data to ensure the integrity and accuracy of the data. Validator tags are added slightly differently when dealing with nested fields. This article will detail how to use validator tags to validate nested fields to help developers better process form data. Whether you're just starting out or an experienced developer, this article will provide you with practical tips and guidance. Let’s learn together!

Question content

This is my code

type abstractaccount struct {
    email        string `gorm:"unique;type:varchar"`
    passwordhash string `gorm:"unique;type:varchar"`
}

type planner struct {
    abstractaccount
}

For example, I want to add a custom validator tag to email via planner

type Planner struct {
    AbstractAccount `validator:"Email:customTag"`
}

Is there a way to implement this in go validator or is there any library that can do this?

Solution

Sample program
In the sample program, there is a function called getFieldsWithCustomTag that takes a reflected value as a parameter and recursively searches for fields with the tag c-tag:true (you can change this). It appends these fields to the slice and, if it encounters a nested structure, calls itself recursively to search for the fields in the nested structure.

The above is the detailed content of How to add validator tag to nested field. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete