Giter VIP home page Giter VIP logo

ozzo-validation's People

Contributors

0perl avatar aradilov avatar asdine avatar cebe avatar erdaltsksn avatar jhvst avatar kfreiman avatar lyoshenka avatar maratori avatar mehran-prs avatar meydjer avatar nathanbaulch avatar necryin avatar petervandenbroek avatar plbogen avatar qiangxue avatar samber avatar seriousben avatar sgleizes avatar terminalfi avatar v4n avatar vbochko avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

ozzo-validation's Issues

Problem with validating slice struct fields

The following test:

func TestInStruct(t *testing.T) {
	var v struct {
		Field []string
	}
	v.Field = []string{"v1"}

	err := ValidateStruct(&v,
		Field(&v.Field, In("v1", "v2")),
	)
	if err != nil {
		t.Fatal(err)
	}
}

Fails with: Field: must be a valid value.

Optional field validation

Hi guys.
Please advise how I can skip validation for empty fields. For example add new rule Optional:

return validation.StructRules{}.
    Add("Gender", validation.Optional, validation.In("Female", "Male")).
    Validate(req, attrs...)

If validation.IsEmpty(field) equal true then we skip validation.In(...). Else we run all next validators. I know about validation.Skip, but I did not find any examples how it use.

Another question: how I can skip validation from custom validator?

Thank you very much for your work.
Regards, Max

Unexpected custom error message from ValidateStruct

Hello again,

it would be really nice if the custom errors from ValidateStruct() had the same format as from Validate(). Right now ValidateStruct() also returns the name of the failed field which makes it hard to use the custom error together with other code. Makes sense?

data := "2123"
err := validation.Validate(data,
	validation.Match(regexp.MustCompile("^[0-9]{5}$")).Error("error.mustbefive"),
)
fmt.Println(err) // Prints: "error.mustbefive"

type Foo struct {
	Bar string
}
t := Foo{Bar: "2123"}
err = validation.ValidateStruct(&t,
	validation.Field(&t.Bar, validation.Match(regexp.MustCompile("^[0-9]{5}$")).Error("error.mustbefive")),
)
fmt.Println(err) // Prints: "Bar: error.mustbefive"

Validation Errors should use JSON tag values as the error keys when marshalling.

Related to #1, when marshalling validation.Errors It would be great if we can detect struct fields with the json tag and use that as the key in the map for validation.Errors.

A option for doing this is to convert validation.Errors to a struct that contains two fields Errs map[string]err & ErrsJSON map[string]string. Errs map key contains the Struct field name and ErrsJSON map key contains the Struct json tag value.

Another option would be to use a custom field tag e.g. validation that is checked for and if specified we use it as the map key for the error message. This isn't specifically meant to be used when marshalling json.

@qiangxue thoughts?

More extensible way of doing validations

Any thoughts or plans or making custom validations more powerful such as allowing sql queries to be executed during the validation?

For example this is how to check if a record is unique in the database (using a ozzo-validation before c5ea90):

// UniqueRecord checks that a value is unique value in the database.
func UniqueRecord(statement string, bindvars ...interface{}) *uniqueRecord {
    return &uniqueRecord{
        message:   "Value is not unique.",
        statement: statement,
        bindvars:  bindvars,
    }
}

type uniqueRecord struct {
    message   string
    statement string
    bindvars  []interface{}
}

func (v *uniqueRecord) Validate(value interface{}, context interface{}) error {
    var exists bool
    statement := "SELECT EXISTS(" + v.statement + ")"
    err := database.SQL.Get(&exists, statement, v.bindvars...)
    if err != nil || exists {
        return errors.New(v.message)
    }
    return nil
}

To validate:

Add("Email", validation.Required, is.Email,     UniqueRecord(
  "SELECT 1 FROM email WHERE email=$1", invitation.Email)
)

This is no longer possible with the updates.
It would be great being able to more than data-type validations and handle SQL queries validation and more complex struct validation such as check if two struct keys are not equal.

[SOLVED] Not working with a float64, don't know why

Hi,
I have the following code :

I defined a structure called Users (I'm using it to query users) :


type Users struct {
  RegisteredAfter  *time.Time `json:"registeredAfter"`
  RegisteredBefore *time.Time `json:"registeredBefore"`

  RangeInKm   *float64      `json:"rangeInKm"`
  Geolocation *common.Point `json:"geolocation"`

  Number int  `json:"number"`
  From   *int `json:"from"`
}

func (u Users) Validate() error {
  validate := validation.ValidateStruct(&u,
    validation.Field(&u.RegisteredAfter, validation.Max(time.Now())),
    validation.Field(&u.RegisteredBefore, validation.Max(time.Now())),

    validation.Field(&u.Number, validation.Required, validation.Max(60)),

    validation.Field(&u.RangeInKm, validation.Min(0), validation.Max(1000)),
    validation.Field(&u.Geolocation),
  )

  return validate
}

And this is the following error I get when I set rangeInKm which is a *float64 :

2018/12/11 12:06:06 VALIDATION rangeInKm: cannot convert float64 to int64.

I don't know why tho.

crossfield struct validation

Hello!

There doesn't seem to be a way to do cross field validation for a struct.

Given:

type Bucket struct {
  Accept []string
  Reject []string
}

How can I write Bucket.Validate with a rule that checks that Accept and Reject are mutually exclusive?

func (b Bucket) Validate() error {
return validation.Validate(&b, validation.By(bucketMutualExclusionCheck)
}

cause an stack overflow because validation.Validate calls Validate on Bucket and so forth... infinite recursion.

The other solution also seems like a hack, because it errors on one or the other field instead of the whole struct:

func (b Bucket) Validate() error {
  return validation.ValidateStruct(&b,
    validation.Field(&b.Accept, validation.By(sliceMutualExclusionCheck(b.Reject))),
  )
}

Is there a better way to tackle this kind of validations?

Issue validating structs in structs

Hello,

I am a new user to Go and of the library and have found what I think is a bug.

I am trying to validate the following struct

type Team struct {
	DisplayName          string   `json:"display_name"`
	TeamDistributionList string   `json:"team_distribution_list"`
	EscalationContact    string   `json:"escalation_contact"`
	ApprovedBillingCodes []string `json:"approved_billing_codes"`
	Membership           struct {
		Maintainers []string `json:"maintainers"`
		Members     []string `json:"members"`
	} `json:"membership"`
	Environments []string `json:"environments"`
}

with the following rules

func (t Team) Validate() error {
	return validation.ValidateStruct(&t,
		validation.Field(&t.DisplayName, validation.Required),
		validation.Field(&t.TeamDistributionList,
			validation.Required
		),
		validation.Field(&t.EscalationContact,
			validation.Required
		),
		validation.Field(&t.ApprovedBillingCodes,
			validation.Required,
			validation.Each(is.Digit),
		),
		validation.Field(&t.Membership.Maintainers, validation.Required, validation.Each(is.Email)),
	)
}

When I run the validation, the following error happens (With the Membership.Maintainers field)

=== RUN   TestTeamValidation
--- FAIL: TestTeamValidation (0.00s)
    team_test.go:19: field #4 cannot be found in the struct

When digging into the error, I've pinpointed the location of the error to https://github.com/go-ozzo/ozzo-validation/blob/master/struct.go#L80

Thanks! If there is any other information I can provide, please let me know :)

Validate if not nil

Considering the following type:

type Foo struct {
    OptionalBar *string
}

Would it be possible to validate OptionalBar only if it's not nil?

Could you help to provide ozzo-widget / ozzo-grid?

Dear Qian,

I am a yii1/yii2 user too, really like that elegant framework which created by you!
In these frameworks, it provide widgets which wrap bootstrap , it is very convenient to developers, especially for the grid widget.

Could you create similar widgets for ozzo framework? It should be increase the stars! Thanks.

Regards,
Scott Huang

Validating Arrays, Slice or Maps should point to an ID / PK

Ozzo, First of all thank you for this library.

But I encountered a challenge where by, when I am validating a slice, I wanted to show the a respective field of that struct. For example;

// Provided this slice ...
addresses := []Address{
    Address{Code: "id1", State: "MD", Zip: "12345"},
    Address{Code: "id2", Street: "123 Main St", City: "Vienna", State: "VA", Zip: "12345"},
    Address{Code: "id3", City: "Unknown", State: "NC", Zip: "123"},
}

I should do something like this

err := validation.Validate(addresses, "Code")
fmt.Println(err)

And it should show

ID1: (City: cannot be blank; Street: cannot be blank.); ID2: (Street: cannot be blank; Zip: must be in a valid format.).

How is that?

How to access individual validation errors

Is there a way to access individual error message like :

type Address struct {
	Street string `json:"street"`
	City   string `json:"city"`
	State  string `json:"state"`
	Zip    string `json:"zip"`
}

// ...perform validation here...

err := a.Validate()
fmt.Println(reflect.ValueOf(err).Kind()) //map
streettError := err["Street"] //is this even possible? <--- give me expression "err" (error) does not support indexing

incorrect struct field name in errors if struct json tag includes omitempty

lets suppose i have this struct

type User struct {
    Username string `json:"username"`
    Password string `json:"password,omitempty"`
}

if there is a validation error on Password the name of the error field will be password,omitempty and below is the json encoded error message

{
    "password,omitempty": "password_required"
}

Missing vendor

See error output:

../../../../../../github.com/go-ozzo/ozzo-validation/is/rules.go:12:2: cannot find package "github.com/asaskevich/govalidator" in any of:
	/usr/local/Cellar/go/1.11/libexec/src/github.com/asaskevich/govalidator (from $GOROOT)
	/Users/Jacky/Jacky.Wu/MyProjects/Go/src/github.com/asaskevich/govalidator (from $GOPATH)

Should we include this vendor?
Thanks.

Validating database nulls types

Hi team.
Please advise how I can validate types like sql.NullBool, sql.NullString, sql.NullInt64, sql.NullFloat64 or advanced packages like https://github.com/guregu/null ? For example, I try to validate:

import (
    "fmt"
    "gopkg.in/guregu/null.v3"
    "github.com/go-ozzo/ozzo-validation"
)

type User struct {
    Name null.String
}

func (u User) Validate(attrs ...string) error {
    return validation.StructRules{}.
        Add("Name", validation.Length(2, 25)).
        Validate(u, attrs...)
}

func main() {
    user := User{Name: null.NewString("", true)}
    if err := validation.Validate(user); err != nil {
        panic(err)
    }
    fmt.Printf("Hello %s", user.Name.String)
}

But receive error cannot get the length of struct. Should I create custom validators or exists better way?

How to return error properly?

How to return correct http status error from validation error?

func SaveHandler(cPtr *routing.Context) error {
    var actor models.Actor
    cPtr.Read(&actor)
    err := actor.Validate()
    if err != nil {
        return err
    }
    return actor.Save()
}
...

func (m *Actor) Save() error {
    err := db.Model(m).Insert()
    if err != nil {
        fmt.Println("Exec err:", err.Error())
    }
    return err
}

Return http 500, and error in json. Is it correct?

Support validating embedded structs

Considering the following:

type ListingOptions struct {
	Offset    int    `json:"offset"`
	Limit     int    `json:"limit"`
	OrderBy   string `json:"order_by"`
	OrderDesc bool   `json:"order_desc"`
}

func (l ListingOptions) Validate() error {
	return validation.ValidateStruct(&l,
		// Offset should be a positive number
		validation.Field(&l.Offset, validation.Min(0)),
		// Limit should be between 10 and 50
		validation.Field(&l.Limit, validation.Min(10), validation.Max(50)),
	)
}

type BookListingOptions struct {
	UserID   int             `json:"user_id"`
	Status   []string       `json:"status"`

	ListingOptions
}

func (l BookListingOptions) Validate() error {
	validOrderColumns := []string{
		"name", "status", "created_at", "updated_at",
	}

	return validation.ValidateStruct(&l,
		// UserID should be a positive number
		validation.Field(&l.UserID, validation.Min(0)),
		// Status should be a valid book status
		validation.Field(&l.Status, validation.In("open", "closed")),
		// ListingOptions.Order should be a valid order clause
		validation.Field(&l.ListingOptions.OrderBy, validation.In(validOrderColumns)),
		// ListingOptions has its own validation
		validation.Field(&l.ListingOptions),
	)
}

Calling BookListingOptions{}.Validate() returns the following error: field #2 cannot be found in the struct

Custom validation rule with additional parameters

Hello

The validation.By method offers no way to use additional parameters.
I would like to modify it to accept a varidic list of parameters after the value to validate, like so:

func checkAbc(value interface{}, args ...interface{}) error {
	s, _ := value.(string)
        caseSensitive, _ := args[0].(bool)
	if !caseSensitive && s != "abc" {
		return errors.New("must be abc")
	}
	if caseSensitive && !EqualFold(s, "abc") {
		return errors.New("must be abc")
	}
	return nil
}

err := validation.Validate("xyz", validation.By(checkAbc, true))

What do you think about it ?

Skip further rules when Nil is found in NilOrNotEmpty Rule

This is a ask for feature where more rules are checked after NilOrNotEmpty only if it was not found to be Nil.

It would be something like:

validation.FIeld(&req.Favoritenumbers, validation.NilOrNotEmpty, validation.By(ValidatePrime), validation.Min(100))

The struct being:

type NewPlayer struct {
Name string `json: "id"`
JerseyNumber int `json:jersey,omitempty"`
}

Where JerseyNumber is optional but if provided it must be a prime number and greater than 100.

Point at the end of the line

type Address struct {
	Street string
}

func Validate(a *Address) error {
	return validation.ValidateStruct(a,
		
		validation.Field(&a.Street, validation.Required, validation.Length(40, 50).Error("NAME_INVALID_LENGHT")),
	)
}

func main() {
	a := &Address{
		Street: "Krasnaya",	
	}

	err := Validate(a)
	fmt.Println(err)  // Street: INVALID_LENGHT.
}

I do not put a dot in the text of the error, where does it come from? remove her

Breaking changes

Heya!

One of the latest updates has removed validation.StructRules, this effectively breaks CI tools like CircleCI.

I love the package and use it quite a lot! But changes that effectively change the API without backwards compatibility make me worried :).

Just a heads up for future commits!

Use ozzo-validation type for validation errors

My use case:

in validators I use repositories and services, the simplest example of such validator "email already exists". This validator goes to check email in db/redis/whatever through repository.

Repository returns user&error.

Error == NotFound means validation passed
Error == nil means email already exists
Error == anythingElse I want to stop validation and handle it in my handler.

And now it's impossible.

I implemented this feature for myself and I would love to bring it to your lib.
But it will break all existing validators. Do you have any ideas how to implement this feature without breaking changes?

Thanks!

P.S. You can take a look at my implementation here: https://github.com/smacker/ozzo-validation

Error message in another language

Are there any way to define error message in another language?
Right now we can define it by using custom error message, but it would be redundant when we validate a bunch of value with the same validation rule.

How can I validation field array ?

I have struct like this

type ReviewJson struct {
	Business string   `json:"business"  form:"business"`
	Feedback string   `json:"feedback" form:"feedback"`
	Point    int      `json:"point" form:"point"`
	Photos   []string `form:"photos[]"`
}

I wanna validation field Photos, for each photo has valid with MongoId.

Partial validation

I'd like to implement a partial update in my API. I can already pass in a list of struct field names to ozzo-dbx's ModelQuery.Update method, but I can't restrict validation to just those fields.

As a workaround, I can check the returned Errors map and remove all the fields I'm not interested in. But would it be possible to add a version of ValidateStruct with an include/exclude feature like ModelQuery.Update?

Comparing Struct Variables

I am trying to validate a struct that has start time and end time as variables. I implemented following to do this. Is there any simpler way to compare those values? If not, this might be a good feature to have.


type TimeRange struct {
	start time.Time
	end time.Time
}

type dateRule struct {
	message  string
	timeRange TimeRange
}


// Error sets the error message for the rule.
func (v *dateRule) Error(message string) *dateRule {
	return &dateRule{
		message: message,
		timeRange: v.timeRange,
	}
}

// Validate checks if the given value is valid or not.
func (v *dateRule) Validate(value interface{}) error {
	timeRange := v.timeRange
	if timeRange.start.After(timeRange.end) {
		return errors.New(v.message)
	}
	return nil
}
//Validation Rules
func (r TemporalRequest) Validate() error {

	var sTime, err1 = utils.ParseDatetime(r.StartTime)

	if err1 != nil {
		return err1
	}
	var eTime, err2 = utils.ParseDatetime(r.EndTime)

	if err2 != nil {
		return err2
	}

	return validation.ValidateStruct(&r,
		validation.Field(&r.StartTime, &dateRule{message: "Start Time should be before end time", timeRange:TimeRange{start:sTime, end:eTime}}),
	)
}

Question `Marshaling vs validation`

There are two common ways for validation in go (at least that I know of):

  1. using tags (eg govalidator)
  2. using explicit validation (like this library)

Both good libraries, but both require using a Validate() function and checking error before using the struct, which is IMO not very convenient having to check every time the struct is used.

I was having this idea of moving validation into custom Unmarshaller.

package main

import (
	"encoding/json"
        "github.com/go-ozzo/ozzo-validation"
	"fmt"
)

type Person struct {
	Name string `"json:name,omitempty"`
	Age  int    `"json:age,omitempty"`
}

func (p *Person) UnmarshalJSON(b []byte) error {
	type Alias Person
	alias := &Alias{}
	err := json.Unmarshal(b, alias)
	if err != nil {
	    return err
	}
	*p = Person(*alias)
	
        // define error checks here
	if p.Age < 18 {
	    return fmt.Errorf("Age must be more than 18")
	}
        // or fields could be validated by using this library 
        return validation.ValidateStruct(p,
            // Age must be more than 18
            validation.Field(p.Age, validation.Min(18)),
        )
	
	return err
}

func main() {

	jsonPerson := []byte(`{"name":"Joye", "age":17}`)
	person := &Person{}
	if err := json.Unmarshal(jsonPerson, person); err != nil {
	    fmt.Println("error decoding json into Person: %v", err)
	    return
	}

	fmt.Println(person)

}

it just seems more convenient (having to just unmarshal rather than validate and unmarshal) also it is easier to set a default value.

could you correct me if I am mistaking or forgeting something

validation.IN cannot parse byte arrays

The validation to check if a value can be found in a given list can not parse byte arrays. I think it is pretty easy to fix. for now i will create a custom function

Validation error of structs with integer constants.

For whatever reason, validating integer constants fails when the value is 0. The following returns with "Code" is required (or something similar). If I change my constants to 1,2 instead of 0,1 it works fine, and if it change OK to NOT_OK in the example (keeping 0,1) below it works fine too.

type ResponseCode int

const (
    OK ResponseCode = 0
     NOT_OK ResponseCode = 1
)

type data struct {
    code: OK,
    something: "foo"
}

func (d Data) Validate() error {
    validation.ValidateStruct(&d, 
        validation.Field(&d.code, validation.Required),
    )
}

Should the IsEmpty check be bypassed for numbers

minAllowed := 1

return validation.Validate(0,
		validation.Min(minAllowed),
		validation.Max(maxAllowed),
	)

I would expect an error from this, as 0 is less than the min value (1), but instead nil is returned. The issue is because (r *ThresholdRule) Validate does a if isNil || IsEmpty(value) { check. Same for Max (what if I want to check if my value 0 satisfies the rule of the min value being 10).

I think that in this context, that check shouldn't be performed. It could be conditionally performed based on reflection (as it does for other reasons).

I'm happy to make a MR to do this.

Edit: I'll add in too while I'm here, thanks for the library!

Pre validation filters concept

Example situations:

  • E-mail validation requires trim extra spaces before the check.
  • Phone number validation requires filter unexpected character.
  • Filename validator may require ToLowerCase filter

Take a look at zend-inputfilter and zend-filter, zend-validator subpackages

$inputFilterConfig = [
    'amount' => [
        'filters'  => [
            ['name' => 'StringTrim']
        ],
        'validators' => [
            ['name' => 'Digits'],
            [
                'name' => 'Between',
                'options' => [
                    'min' => 1,
                    'max' => 10
                ]
            ]
        ]
    ],
    'email' => [
        'filters'  => [
            ['name' => 'StringTrim'],
            ['name' => 'ToLowerCase'],
        ],
        'validators' => [
            ['name' => 'EmailAddress']
        ]
    ]
];

Govalidator not installable due to Gopkg issues

When installing the dependency gopkg.in/asaskevich/govalidator.v4 the following error occurs.

error: RPC failed; HTTP 301 curl 22 The requested URL returned error: 301
fatal: The remote end hung up unexpectedly
package gopkg.in/asaskevich/govalidator.v4: exit status 128

This is because git no longer follows redirects niemeyer/gopkg#50

There hasn't been any updates from the Gopkg author on the issue for a while. I would recommend to usegithub.com/asaskevich/govalidator so that this library is installable out of the box.

Building failed with vgo

Building failed with vgo. :(

go: finding github.com/go-ozzo/ozzo-routing latest
go: finding github.com/go-ozzo/ozzo-routing/access latest
go: finding github.com/go-ozzo/ozzo-routing/fault latest
go: finding github.com/go-ozzo/ozzo-routing/file latest
go: finding github.com/go-ozzo/ozzo-routing/cors latest
go: finding github.com/go-ozzo/ozzo-routing/content latest
go: finding github.com/go-ozzo/ozzo-routing/auth latest
go: finding github.com/ikeikeikeike/go-sitemap-generator/stm latest
go: finding github.com/ikeikeikeike/go-sitemap-generator latest
go: finding github.com/go-ozzo/ozzo-validation/is latest
go: finding github.com/go-ozzo/ozzo-validation latest
go: extracting github.com/go-ozzo/ozzo-validation v0.0.0-20180719025158-48037855ba41
-> unzip D:\Go\src\mod\cache\download\github.com\go-ozzo\ozzo-validation\@v\v0.0.0-20180719025158-48037855ba41.zip: invalid file name github.com/go-ozzo/[email protected]/.gitignore
go: finding github.com/go-ozzo/ozzo-routing/slash latest
go: finding github.com/jordan-wright/email latest
go: import "kassar/cmd/server" ->
	import "kassar/app" ->
	import "github.com/go-ozzo/ozzo-validation": cannot find module providing package github.com/go-ozzo/ozzo-validation
go: import "kassar/cmd/server" ->
	import "kassar/apis" ->
	import "kassar/models" ->
	import "github.com/go-ozzo/ozzo-validation/is": cannot find module providing package github.com/go-ozzo/ozzo-validation/is

struct cross field validation

Is it possible to create a custom validation rule to do a cross field validation in a struct fields with validation.ValidateStruct?

thanks

Error validating integer value

package model

import (
    "github.com/go-ozzo/ozzo-validation"
    "github.com/go-ozzo/ozzo-validation/is"
)

type UserConfirmation struct {
	ID int64 `json:"id" meddler:"id,pk"`
	UserID int64 `json:"user_id" meddler:"user_id" validation:"user_id"`
	Type string `json:"type" meddler:"type"`
	Code string `json:"-" meddler:"code"`
	Time int32 `json:"expire" meddler:"timestamp"`
}

func (uc UserConfirmation) Validate() error {
    return validation.StructRules{}.
        Add("UserID", validation.Required, is.Int).
        Add("Type", validation.Required, validation.In("sms","email")).
        Validate(uc)
}

and some main.go code

confirmation := &model.UserConfirmation{}
_ := c.BindJSON(confirmation)
errs := confirmation.Validate()
if errs != nil {
    errs := errs.(validation.Errors)
    c.JSON(http.StatusBadRequest, gin.H{
        "errors": errs,
    })
    return
}

Sending integer user_id value

curl -XPOST localhost:8080/api/auth/confirmation/send -d '{"user_id":4,"type":"sms"}'
{"errors":{"user_id":"must be either a string or byte slice"}}

It ask me to send a string.... But i need an int value. And sending a string causes struct error:

curl -XPOST localhost:8080/api/auth/confirmation/send -d '{"user_id":"asdsa","type":"sms"}'
{"error":"json: cannot unmarshal string into Go value of type int64"}

Any ideas? I'm new in go)

Panic on struct field pointing to zero value

When using ValidateStruct on a struct that has a field using a pointer to any field that contains a zero value, the validation panics.

package main

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

type A struct {
	Name *string
}

func (a *A) Validate() error {
	return validation.ValidateStruct(a,
		validation.Field(&a.Name, validation.Length(1, 32)),
	)
}
func main() {
	var a A
	a.Validate()
}
$ go run main.go
panic: reflect: call of reflect.Value.Type on zero Value

goroutine 1 [running]:
panic(0x117440, 0xc420206800)
	/usr/local/go/src/runtime/panic.go:500 +0x1a1
reflect.Value.Type(0x0, 0x0, 0x0, 0x0, 0x0)
	/usr/local/go/src/reflect/value.go:1670 +0x224
github.com/go-ozzo/ozzo-validation.Validate(0x119ca0, 0x0, 0xc420193c90, 0x1, 0x1, 0x196, 0xc4202052d0)

Suggestion for library improvement

This library is great. I had been looking for a library that would be as elegant and flexible as the NodeJS Joi library developed by Walmart for their hapijs framework and I found this library that was the closest thing to the Joi library. I would like to make the following suggestions to improve the library.

  • Field names passed in to the validator should be pointer based instead of a string. For example, use &c.Name instead of "Name". This would move the error for using the wrong field name from a runtime error to a compile time error.
  • Incorporate the validation rules from the goburrow validator into the go-ozzo validator which have been really thought out and powerful. For example goburrow has the "min" validation rule, which applies the rule depending upon what has been passed in. If a string is passed in, then it checks for the minimum length. If a slice has been passed in, then it checks for the length of the array. If an integer has been passed in, then it checks if the value is equal to or greater than the min value. And so on...

Thanks for a great library!

Pointer returns

I was browsing the docs and thought that this is a great looking library. However I don't understand why the rules like LengthRule are returned as a pointer.

https://github.com/go-ozzo/ozzo-validation/blob/master/length.go#L48

It's my understanding that a struct that is this small belongs on the stack, and by creating all these pointers in a heavy-usage scenario like an API where many models are constantly being validated is going to create unnecessary pressure on the GC. Any reasoning behind this? Is it too late to change it?

Min() validator fails on uint32 field

I stumbled upon this when trying to validate a struct with uint32 field. The validation fails with

Integer: cannot convert uint32 to int64.

Here's a complete test case:

package main

import (
	"fmt"
	"testing"

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

type A struct {
	Integer uint32
}

func (a A) Validate() error {
	return validation.ValidateStruct(&a,
		validation.Field(&a.Integer, validation.Required, validation.Min(1)))
}

func TestValidate(t *testing.T) {
	a := A{2}
	err := a.Validate()
	if err != nil {
		fmt.Printf("validation error received: %s", err.Error())
		t.Fail()
	}
}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.