Validator: Can I have one choice list validation?

Created on 21 Jun 2016  路  5Comments  路  Source: go-playground/validator

Example: validate([]string{"A", "B", "C"}, value)

question

Most helpful comment

Oh OK, yes totally doable with or's in the tag

eg.

package main

import (
    "fmt"

    "gopkg.in/go-playground/validator.v8"
)

var (
    validate *validator.Validate
)

func main() {

    config := &validator.Config{
        TagName: "validate",
    }

    validate = validator.New(config)

    fld := []string{"M", "F", "O"}


    errs := validate.Field(fld, "dive,eq=M|eq=F|eq=O")
    fmt.Println(errs)
}

dive - tells the library to go into/dive into the array
eq=M|eq=F|eq=O - says any value in the array must be equal to M or F or O

if using on a single field and not an array, just remove the dive tag.

does this example explain what your looking for?

All 5 comments

I'm not quite sure what you mean, do you mean ability to validate []string on it's own and not part of a struct?

or

validate a single element within a []string but not the others?

there is the ability to validate any field individually using validate.Field example shown here

I have a gender field with values: "M" | "F" | "O". I need an way to validate choice values as: validate(FieldValue,

Oh OK, yes totally doable with or's in the tag

eg.

package main

import (
    "fmt"

    "gopkg.in/go-playground/validator.v8"
)

var (
    validate *validator.Validate
)

func main() {

    config := &validator.Config{
        TagName: "validate",
    }

    validate = validator.New(config)

    fld := []string{"M", "F", "O"}


    errs := validate.Field(fld, "dive,eq=M|eq=F|eq=O")
    fmt.Println(errs)
}

dive - tells the library to go into/dive into the array
eq=M|eq=F|eq=O - says any value in the array must be equal to M or F or O

if using on a single field and not an array, just remove the dive tag.

does this example explain what your looking for?

Hey @phenrigomes just checking if my example was what you were looking for?

@joeybloggs is there a way to make this validation case insensitive ?

Was this page helpful?
0 / 5 - 0 ratings

Related issues

deschmih picture deschmih  路  3Comments

jdgordon picture jdgordon  路  4Comments

0505gonzalez picture 0505gonzalez  路  3Comments

romangithub1024 picture romangithub1024  路  5Comments

phamduong picture phamduong  路  6Comments