简体   繁体   中英

How to chain validations together using Golang go-playground/validator?

I am using https://github.com/go-playground/validator for a REST API server. I am using the same struct for different endpoint with different validation requirement. For example, /users/login requires only email and password . However, to create a user, more information like firstName would be required.

So I think using struct tag to validate is not very convenient. Checking the variable as described in this example seems more appropriate. However I run into two problems:

  1. I am checking multiple at the same time. Is there a way to chain a series of validation together? Checking every single variable in a struct then check for error makes it harder to code and harder to read.

  2. The error object is really empty. For example, checking if email is required shows only err.Tag() and err.ActualTag() as required and err.Kind() and err.Type() as string and nothing else. Does the validator provide anything that makes this a little more convenient?

I use ozzo-validation . it uses normal programming constructs rather than error-prone struct tags to specify how data should be validated. I recommend you to define different validation function/method for each use-case(request).

func ValidateLogin(req) {
err := validation.Validate(req.Username,
        validation.Required,       // 
        is.Email)
...
}

func ValidateRegister(req) {
...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM