asaskevich / govalidator

[Go] Package of validators and sanitizers for strings, numerics, slices and structs
MIT License
6.05k stars 555 forks source link

Validation does not accept empty string for "*string" property #274

Closed tretkow closed 4 years ago

tretkow commented 6 years ago

Steps to reproduce:

package main

import (
    "testing"

    "github.com/asaskevich/govalidator"
)

type A struct {
    Name string `json:"name,omitempty" valid:"length(0|10),optional"`
}

type B struct {
    Name *string `json:"name,omitempty" valid:"length(0|10),optional"`
}

// This works
func TestA(t *testing.T) {
    a := &A{Name: ""}

    valid, err := govalidator.ValidateStruct(a)
    if !valid || err != nil {
        t.Error("Incorrect validation result")
    }
}

// This does not work
func TestB(t *testing.T) {
    emptyString := ""
    b := &B{Name: &emptyString}

    valid, err := govalidator.ValidateStruct(b)
    if !valid || err != nil {
        t.Errorf("Incorrect validation result: %v, %v", valid, err)
    }
}

Result:

➜  govalidator go test .
--- FAIL: TestB (0.00s)
        govalidator_test.go:32: Incorrect validation result: false, name: The following validator is invalid or can't be applied to the field: "length(0|10)"
asaskevich commented 4 years ago

Fixed in #329