Skip to content

How can I validate a single value? #1822

Answered by aldas
AngangGuo asked this question in Q&A
Discussion options

You must be logged in to vote

What you want to do is to:

  1. bind path parameter to struct
  2. validate that field

Path parameter can be bind to struct with param="id" tag
Validation can be added with field tag validate:"gt=1,lt=10"

so you need to add similar field to your bindable struct
ID int64 `param:"id" validate:"required,gt=1,lt=10"`

If you do not want to use struct then you need to first convert path param to int and then use validator.Var on it.

		var id int64
		if err = echo.PathParamsBinder(c).Int64("id", &id).BindError(); err != nil {
			return echo.NewHTTPError(http.StatusBadRequest, err.Error())
		}

		if err = validator.New().Var(id, "gt=1,lt=10"); err != nil {
			return echo.NewHTTPError(http.StatusBadRequest

Replies: 1 comment 1 reply

Comment options

You must be logged in to vote
1 reply
@AngangGuo
Comment options

Answer selected by AngangGuo
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants