{"id":18259962,"url":"https://github.com/theflyingcodr/govalidator","last_synced_at":"2025-09-11T10:36:22.044Z","repository":{"id":46193171,"uuid":"333961351","full_name":"theflyingcodr/govalidator","owner":"theflyingcodr","description":"A simple request validator for go with a fluent api","archived":false,"fork":false,"pushed_at":"2024-02-19T12:17:16.000Z","size":118,"stargazers_count":5,"open_issues_count":1,"forks_count":4,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-03-20T17:38:24.095Z","etag":null,"topics":["error-handlers","go","golang","inline","validation","validation-library"],"latest_commit_sha":null,"homepage":"","language":"Go","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/theflyingcodr.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2021-01-28T21:29:36.000Z","updated_at":"2023-04-05T05:58:01.000Z","dependencies_parsed_at":"2024-06-19T16:04:05.879Z","dependency_job_id":"b0ba76ed-3737-461c-805f-2959df640ae6","html_url":"https://github.com/theflyingcodr/govalidator","commit_stats":null,"previous_names":[],"tags_count":5,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/theflyingcodr%2Fgovalidator","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/theflyingcodr%2Fgovalidator/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/theflyingcodr%2Fgovalidator/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/theflyingcodr%2Fgovalidator/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/theflyingcodr","download_url":"https://codeload.github.com/theflyingcodr/govalidator/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":247238357,"owners_count":20906432,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["error-handlers","go","golang","inline","validation","validation-library"],"created_at":"2024-11-05T10:41:15.614Z","updated_at":"2025-04-04T19:33:03.643Z","avatar_url":"https://github.com/theflyingcodr.png","language":"Go","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Validator [![Go Reference](https://pkg.go.dev/badge/github.com/theflyingcodr/govalidator.svg)](https://pkg.go.dev/github.com/theflyingcodr/govalidator) [![Go Report Card](https://goreportcard.com/badge/github.com/theflyingcodr/govalidator)](https://goreportcard.com/report/github.com/theflyingcodr/govalidator) [![CI Status](https://github.com/theflyingcodr/govalidator/workflows/Go/badge.svg)](https://github.com/theflyingcodr/govalidator/actions?query=workflow%3AGo)\n\nThis is a simple input validator for go programs which can be used to test inputs at the boundary of your application.\n\nIt uses a fluent API to allow chaining of validators to keep things concise and terse.\n\nThere is also a provided Validator interface which can applied to structs and tested in the like of http handlers or error handlers.\n\n## Installation\n\nGoValidator now utilises generics toi reduce the number of function duplication previously required. This requires go1.18 or above. \n\nIf you wish to have the version that doesn't require generics (this is no longer maintained), install as shown:\n\n```bash\ngo get github.com/theflyingcodr/govalidator@v0.1.3\n```\n\nTo get the latest version with Generics, install using the below:\n\n```bash\ngo get github.com/theflyingcodr/govalidator/v2\n```\n\n## Error structure\n\nValidation functions are ran per field and multiple functions can be evaluated per field.\n\nAny validation errors found are then stored in a map[string][]string. This can be printed using the .String() method or can be encoded to Json and wrapped in an `errors` object for example.\n\nFor an idea of the json output see this below example validation error:\n\n```json\n{\n    \"errors\": {\n        \"count\": [\n            \"value 0 should be greater than 0\"\n        ],\n        \"isEnabled\": [\n            \"value true does not evaluate to false\"\n        ]\n    }\n}\n```\n\nIn this example I wanted my errors to be wrapped in an errors object, you may just want them output raw and unwrapped or wrapped in something else.\n\nThis is up to you to decide how best to handle the presentation of the error list.\n\n## Usage\n\nThere are two main ways of using the library, either via inline checks or by implementing the `validator.Validator` interface.\n\nTo get started though, call `validator.New()`.\n\nFrom this you can then chain validators, the idea is you supply the field name and then a series of one or more validator functions.\n\n### Inline Chaining\n\nBelow is an inline method shown, this shows the fluent nature of the API allowing chaining of validators.\n\nEach Validate call is for a single field but multiple validator functions can be added per field as can be seen for the \"dob\" field.\n\n```go\n    func(s *svc) Create(ctx context.Context, req Request) error{\n        if err := validator.New().\n            Validate(\"name\", validator.Length(req.Name, 4, 10)).\n            Validate(\"dob\", validator.NotEmpty(req.DOB), validator.DateBefore(req.DOB, time.Now().AddDate(-16, 0, 0))).\n            Validate(\"isEnabled\", validator.Bool(req.IsEnabled, false)).\n            Validate(\"count\", validator.PositiveInt(req.Count)).Err(); err != nil {\n                return err\n        }\n    }\n```\n\n*Note* - the final call here is the `.Err()` method, this will return nil if no errors are found or error if one or more have been found.\n\n### Struct Validation\n\nThe second method to validate is by implementing the validator.Validator interface on a struct.\n\nThe interface is very simple:\n\n```go\n    type Validator interface {\n        Validate() ErrValidation\n    }\n```\n\nTaking an example from the [examples directory](examples), you can apply to a struct as shown:\n\n```go\n    type Request struct {\n        Name      string    `json:\"name\"`\n        DOB       time.Time `json:\"dob\"`\n        IsEnabled bool      `json:\"isEnabled\"`\n        Count     int       `json:\"count\"`\n    }\n    \n    // Validate implements validator.Validator and evaluates Request.\n    func (r *Request) Validate() validator.ErrValidation {\n        return validator.New().\n            Validate(\"name\", validator.Length(r.Name, 4, 10)).\n            Validate(\"dob\", validator.NotEmpty(r.DOB), validator.DateBefore(r.DOB, time.Now().AddDate(-16, 0, 0))).\n            Validate(\"isEnabled\", validator.Bool(r.IsEnabled, false)).\n            Validate(\"count\", validator.PositiveInt(r.Count))\n    }\n```\n\nThis is an ideal usecase for handling common errors in a global error handler, you can simply parse your requests, check, if they implement the interface and evaluate the struct. An Example of this is found in the [examples](examples).\n\n## Examples\n\nThere are examples in the [examples directory](examples), you can clone the repo and have a play with these to ensure the validator meets your needs.\n\n## Functions\n\nAll functions are currently located in the [functions](functions.go) file.\n\nThese must return a validator.ValidationFunc function and can be wrapped to allow custom params to be passed.\n\nHere is an example from the functions.go file:\n\n```go\n    func Length(val string, min, max int) ValidationFunc {\n        return func() error {\n            if len(val) \u003e= min \u0026\u0026 len(val) \u003c= max {\n                return nil\n            }\n            return fmt.Errorf(validateLength, val, min, max)\n        }\n    }\n```\n\nPretty simple! You can add your own compatible functions in your code base and call them in the Validate(..,...) methods.\n\nYou can also apply one time functions to the Validate calls as shown:\n\n```go\n    Validate(\"name\", validator.Length(name, 1, 20), func() error{\n        if mything == 0{\n            return fmt.Errorf(\"oh no\")\n        }\n        return nil\n    })\n```\n\n## Contributing\n\nI've so far added a limited set of validation functions, if you have an idea for some useful functions feel free to open an issue and PR.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ftheflyingcodr%2Fgovalidator","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Ftheflyingcodr%2Fgovalidator","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ftheflyingcodr%2Fgovalidator/lists"}