Object schema description language and validator for golang. (Inspired by Hapi.js Joi library)
$ go get github.com/softbrewery/gojoi
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
- gojoi
Generates a schema object that matches any data type.
schema := joi.Any()
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"
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...)
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...)
Marks a key as required which will not allow nil
as value. All keys are optional by default.
schema := joi.Any().Required()
Marks a key as forbidden which will not allow any value except nil
. Used to explicitly forbid keys.
schema := joi.Any().Forbidden()
Requires the value to be a zero value (go default init value)
schema := joi.Any().Zero()
Requires the value to be a non-zero value (go default init value)
schema := joi.Any().NonZero()
Annotates the key where:
desc
- the description string.
schema := joi.Any().Description("my description")
Allows to run custom tranformation functions where:
stage
- defines the stage that triggers this transformfn
- function that will be executes
Allowed staged:
joi.TransformStagePRE
- Executes before the validation startsjoi.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
Generates a schema object that matches string data type.
Supports the same methods of the any() type.
schema := joi.String()
Specifies the minimum number string characters where:
limit
- the minimum number of string characters required.
schema := joi.String().Min(2)
Specifies the maximum number string characters where:
limit
- the maximum number of string characters allowed.
schema := joi.String().Max(10)
Specifies the exact string length required where:
limit
- the required string length.
schema := joi.String().Length(5)
Requires the string value to be all uppercase.
schema := joi.String().UpperCase()
Requires the string value to be all lowercase.
schema := joi.String().LowerCase()
Defines a regular expression rule where:
expression
- a regular expression object the string value must match against.
schema := joi.String().Regex("^[abc]+$")
Requires the number to be a credit card number Using Luhn Algorithm.
schema := joi.String().CreditCard()
Requires the string value to be a valid base64 string; does not check the decoded value.
schema := joi.String().Base64()
Requires the string value to be a valid hexadecimal string.
schema := joi.String().Hex()
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,
})
Generates a schema object that matches int data type.
Supports the same methods of the any() type.
schema := joi.Int()
Specifies the minimum number where:
limit
- the minimum number required.
schema := joi.Int().Min(2)
Specifies the maximum number where:
limit
- the maximum number allowed.
schema := joi.Int().Max(10)
Requires the number to be positive.
schema := joi.Int().Positive()
Requires the number to be negative.
schema := joi.Int().Negative()
Specifies that the value must be greater than limit.
limit
- the lower limit
schema := joi.Int().Greater(10)
Specifies that the value must be less than limit.
limit
- the upper limit
schema := joi.Int().Less(10)
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
Generates a schema object that matches bool data type.
Supports the same methods of the any() type.
schema := joi.Bool()
Generates a schema object that matches slice [] data type.
Supports the same methods of the any() type.
schema := joi.Slice()
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)
Specifies the minimum number of items in the slice where:
limit
- the lowest number of array items allowed.
schema := joi.Slice().Min(2)
Specifies the maximum number of items in the slice where:
limit
- the highest number of array items allowed.
schema := joi.Slice().Max(10)
Specifies the exact number of items in the slice where:
limit
- the number of array items allowed.
schema := joi.Slice().Length(5)
Generates a schema object that matches struct data type.
Supports the same methods of the any() type.
schema := joi.Struct()
Sets the allowed object keys where:
keys
- object where each key is assigned a joi type object. keys is ofStructKeys
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(),
}),
})