gojoi

module
v0.0.0-...-34d5e10 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 23, 2018 License: MIT

README

gojoi Logo

gojoi

Object schema description language and validator for golang. (Inspired by Hapi.js Joi library)

Build Status codecov Go Report Card GitHub license

Install

$ go get github.com/softbrewery/gojoi

Usage

Usage is a two steps process;

First, a schema is constructed:

schema := joi.String()

Then the value is validated against the schema:

err := joi.Validate("hello", schema)

If the input is valid, then the error will be nil, otherwise it will be an Error object.

Example to validate slice of strings:

schema := joi.Slice().Items(
    joi.String(),
)

data := []string{"hello", "world"}

err := joi.Validate(data, schema)

// err == nil

Table of Contents - API


Api

Any

Generates a schema object that matches any data type.

schema := joi.Any()
Any().Kind()

Gets the type of the schema

kind := joi.Any().Kind() // kind == "interface"
kind := joi.String().Kind() // kind == "string"
kind := joi.Int().Kind() // kind == "int"
kind := joi.Bool().Kind() // kind == "bool"
kind := joi.Slice().Kind() // kind == "slice"
kind := joi.Struct().Kind() // kind == "struct"
Any().Allow(values ...interface{})

Whitelists a value where:

  • value - the allowed value which can be of any type and will be matched against the validated value before applying any other rules. value can be a slice of values, or multiple values can be passed as individual arguments.

Pass in single or multiple arguments

schema1 := joi.Any().Allow("id", "name")
schema2 := joi.Any().Allow(0, 10, 200)
schema3 := joi.Any().Allow(true)

Pass in a slice

data := []string{"id", "name", "isbn"}
schema := joi.Any().Allow(data...)
Any().Disallow(values ...interface{})

Blacklists a value where:

  • value - the forbidden value which can be of any type and will be matched against the validated value before applying any other rules. value can be an array of values, or multiple values can be passed as individual arguments.

Pass in single or multiple arguments

schema1 := joi.Any().Disallow("id", "name")
schema2 := joi.Any().Disallow(0, 10, 200)
schema3 := joi.Any().Disallow(true)

Pass in a slice

data := []string{"id", "name", "isbn"}
schema := joi.Any().Disallow(data...)
Any().Required()

Marks a key as required which will not allow nil as value. All keys are optional by default.

schema := joi.Any().Required()
Any().Forbidden()

Marks a key as forbidden which will not allow any value except nil. Used to explicitly forbid keys.

schema := joi.Any().Forbidden()
Any().Zero()

Requires the value to be a zero value (go default init value)

schema := joi.Any().Zero()
Any().NonZero()

Requires the value to be a non-zero value (go default init value)

schema := joi.Any().NonZero()
Any().Description(desc string)

Annotates the key where:

  • desc - the description string.
schema := joi.Any().Description("my description")
Any().Transform(stage TransformStage, fn TransformFunc)

Allows to run custom tranformation functions where:

  • stage - defines the stage that triggers this transform
  • fn - function that will be executes

Allowed staged:

  • joi.TransformStagePRE - Executes before the validation starts
  • joi.TransformStagePOST - Executes after the validation has finished

Use this functionality to:

  • Inject custom validators
  • Transform or normalize values

TransformFunc type definition

type TransformFunc func(oldValue interface{}) (newValue interface{}, error)
// Tranform function
fn := func(value interface{}) (interface{}, error) {

    cValue, ok := value.(string)
    if !ok {
        return nil, errors.New("Failed to cast type")
    }

    if cValue == "id" {
        cValue = "name"
    }
    
    return cValue, nil
}

// Build schema
schema := joi.Any().Allow("name").Transform(joi.TransformStagePRE, fn)

// Validate
err := joi.Validate("id", schema) // err == nil

String - inherits from Any

Generates a schema object that matches string data type.

Supports the same methods of the any() type.

schema := joi.String()
String().Min(limit int)

Specifies the minimum number string characters where:

  • limit - the minimum number of string characters required.
schema := joi.String().Min(2)
String().Max(limit int)

Specifies the maximum number string characters where:

  • limit - the maximum number of string characters allowed.
schema := joi.String().Max(10)
String().Length(limit int)

Specifies the exact string length required where:

  • limit - the required string length.
schema := joi.String().Length(5)
String().UpperCase()

Requires the string value to be all uppercase.

schema := joi.String().UpperCase()
String().LowerCase()

Requires the string value to be all lowercase.

schema := joi.String().LowerCase()
String().Regex(expression string)

Defines a regular expression rule where:

  • expression - a regular expression object the string value must match against.
schema := joi.String().Regex("^[abc]+$")
String().CreditCard()

Requires the number to be a credit card number Using Luhn Algorithm.

schema := joi.String().CreditCard()
String().Base64()

Requires the string value to be a valid base64 string; does not check the decoded value.

schema := joi.String().Base64()
String().Hex()

Requires the string value to be a valid hexadecimal string.

schema := joi.String().Hex()
String().Email(options *EmailOptions)

Requires the string value to be a valid email address.

  • options - optional settings, options is of type *EmailOptions
    • SMTPLookup - Defines if SMTP lookup need to be executed (defaults to false)

Example without options

schema := joi.String().Email(nil)

Example with options

schema := joi.String().Email(&EmailOptions{
    SMTPLookup: true,
})

Int - inherits from Any

Generates a schema object that matches int data type.

Supports the same methods of the any() type.

schema := joi.Int()
Int().Min(limit int)

Specifies the minimum number where:

  • limit - the minimum number required.
schema := joi.Int().Min(2)
Int().Max(limit int)

Specifies the maximum number where:

  • limit - the maximum number allowed.
schema := joi.Int().Max(10)
Int().Positive()

Requires the number to be positive.

schema := joi.Int().Positive()
Int().Negative()

Requires the number to be negative.

schema := joi.Int().Negative()
Int().Greater(limit int)

Specifies that the value must be greater than limit.

  • limit - the lower limit
schema := joi.Int().Greater(10)
Int().Less(limit int)

Specifies that the value must be less than limit.

  • limit - the upper limit
schema := joi.Int().Less(10)
Int().Multiple(base int)

Specifies that the value must be a multiple of base:

  • base - the base to multiply
schema := joi.Int().Multiple(3)

Notes: uses the modulo operator (%) to determine if a number is multiple of another number


Bool - inherits from Any

Generates a schema object that matches bool data type.

Supports the same methods of the any() type.

schema := joi.Bool()

Slice - inherits from Any

Generates a schema object that matches slice [] data type.

Supports the same methods of the any() type.

schema := joi.Slice()
Slice().Items(schema Schema)

Lists the types allowed for the array values where:

  • schema - a joi schema object to validate each array item against. schema can be an array of values, or multiple values can be passed as individual arguments.
schema := joi.Slice().Items(
    joi.String(),
).Max(10)
Slice().Min(limit int)

Specifies the minimum number of items in the slice where:

  • limit - the lowest number of array items allowed.
schema := joi.Slice().Min(2)
Slice().Max(limit int)

Specifies the maximum number of items in the slice where:

  • limit - the highest number of array items allowed.
schema := joi.Slice().Max(10)
Slice().Length(limit int)

Specifies the exact number of items in the slice where:

  • limit - the number of array items allowed.
schema := joi.Slice().Length(5)

Struct - inherits from Any

Generates a schema object that matches struct data type.

Supports the same methods of the any() type.

schema := joi.Struct()
Struct().Keys(keys StructKeys{...})

Sets the allowed object keys where:

  • keys - object where each key is assigned a joi type object. keys is of StructKeys

StructKeys is of type: map[string]Schema

Basic example:

schema := joi.Struct().Keys(StructKeys{
    "Name": joi.String(),
})

Advanced example:

schema := joi.Struct().Keys(StructKeys{
    "ID": joi.Zero(),
    "Name": joi.String().NonZero(),
    "Tags": joi.Slice().Items(
        joi.String().UpperCase().Length(4),
    ).Max(10),
    "Meta": joi.Struct(StructKeys{
        "Active": joi.Bool(),
    }),
})

Directories

Path Synopsis
pkg
joi

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL