Skip to content

Repository files navigation

validate

Go Reference

Input validation made easy for Go interface methods.

Installation

Make a custom build of protogo:

$ protogo build --plugin=github.com/protogodev/validate

Or build from a local fork:

$ protogo build --plugin=github.com/protogodev/validate=../my-fork
Usage
$ protogo validate -h
Usage: protogo validate <source-file><interface-name>
Arguments:
<source-file>source file
<interface-name> interface name
Flags:
-h, --help Show context-sensitive help.
--out="." output directory
--fmt whether to make the generated code formatted
--custom=STRING the declaration file of custom validators

Quick Start

NOTE: The following code is located in helloworld.

  1. Define the interface

    typeServiceinterface {
    SayHello(ctx context.Context, namestring) (messagestring, errerror)
    }
  2. Implement the service

    typeGreeterstruct{}
    func (g*Greeter) SayHello(ctx context.Context, namestring) (string, error) {
    return"Hello "+name, nil
    }
  3. Add the validation annotations

    typeServiceinterface {
    // @schema:// name: len(0, 10) && match(`^\w+$`)SayHello(ctx context.Context, namestring) (messagestring, errerror)
    }
  4. Generate the validation middleware

    $ cd examples/helloworld
    $ protogo validate ./service.go Service
  5. Use the middleware for input validation

    funcmain() {
    varsvc helloworld.Service=&helloworld.Greeter{}
    svc=helloworld.ValidateMiddleware(nil)(svc)
    message, err=svc.SayHello(context.Background(), "!Tracey")
    fmt.Printf("message: %q, err: %v\n", message, err)
    // Output:// message: "", err: name: INVALID(invalid format)
    }

Validation Syntax

Operator / ValidatorValidating / Vext Equivalent(s)Example
!Not!lt(0)
&&All / Andgt(0) && lt(10)
||Any / Oreq(0) || eq(1)
nonzeroNonzerononzero
zeroZerozero
lenLenString / LenSlicelen(0, 10)
runecntRuneCountrunecnt(0, 10)
eqEqeq(1)
neNene(2)
gtGtgt(0)
gteGtegte(0)
ltLtlt(10)
lteLtelte(10)
xrangeRangexrange(0, 10)
inInin(0, 1)
ninNinnin("Y", "N")
matchMatchmatch(`^\w+$`)
emailEmailemail
ipIPip
timeTimetime("2006-01-02T15:04:05Z07:00")
_A special validator that means to use the nested Schema() of the struct argument._

Examples

See examples.

Documentation

Check out the documentation.

License

MIT

About

Input validation made easy for Go interface methods.

Resources

Stars

8 stars

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages