go-ozzo / ozzo-validation

An idiomatic Go (golang) validation package. Supports configurable and extensible validation rules (validators) using normal language constructs instead of error-prone struct tags.
MIT License
3.73k stars 224 forks source link

Adding a new validator for Not-In #40

Closed plbogen closed 6 years ago

plbogen commented 6 years ago

Currently there is an In validator that checks if a value matches one of a list of permissible items. This is great for implementing a whitelist check of validating an item is a valid choice from multiple choices.

What it does not allow is you to check if a value is unique or if it is not a forbidden value. This validator allows both to be checked.

Unique can be done by doing the check against a variable that is then updated after the entry with the current value.

package main

import (
    "fmt"

    "github.com/go-ozzo/ozzo-validation"
)

var seen = []string{}

type Address struct {
    Street string
    City   string
    State  string
    Zip    string
}

func (a *Address) Validate() error {
    result := validation.ValidateStruct(a,
        validation.Field(a.Street, validation.NotIn(seen)),
    )
    seen = append(seen, a.Street)

    return result
}

func main() {
    addresses := []Address{
        Address{Street: "123 Main St", City: "Richmand", State: "MD", Zip: "12345"},
        Address{Street: "123 Main St", City: "Vienna", State: "VA", Zip: "12345"},
        Address{Street: "125 Main St", City: "Unknown", State: "NC", Zip: "12345"},
    }
    err := validation.Validate(addresses)
    fmt.Println(err)
}
coveralls commented 6 years ago

Coverage Status

Coverage remained the same at 100.0% when pulling 4bea8f5c3a79f9e302469712f7a626a9803bbf2a on plbogen:master into 44af65fe9adfdf78a5ba44f41f5d1fd6a9c4920e on go-ozzo:master.

coveralls commented 6 years ago

Coverage Status

Coverage remained the same at 100.0% when pulling 4bea8f5c3a79f9e302469712f7a626a9803bbf2a on plbogen:master into 44af65fe9adfdf78a5ba44f41f5d1fd6a9c4920e on go-ozzo:master.

qiangxue commented 6 years ago

Thanks!

cqueinnec commented 4 years ago

Hi, just wanted to highlight that this appreciated feature is not listed in Built-in Validation Rules.

qiangxue commented 4 years ago

Fixed. Thanks!