Skip to content
Robin edited this page May 16, 2015 · 9 revisions

In order to specify how fields of a structure should be validated, fields must be tagged with the validate tag.

Syntax

method_name                    // No parameters, same as method_name().
method_name()                  // No parameters, same as method_name.
method_name(param1)            // Unbounded string parameter, same as ´param1´, results in "param1".
method_name(´bounded param1´)  // Bounded string parameter, results in "bounded param1".
method_name(´par\´am1´)        // Bounded and escaped string parameter, results in "par´am1".
method_name(param1, param2)    // Multiple parameters.
method_name(123, 123.456)      // Numeric parameter.
method_name(true, false)       // Boolean parameter.
method_name(nil, null)         // Nil parameter. 'null' is an alias for 'nil'.
method_name,other_method_name  // Validator method AND operator, same as (method_name AND other_method_name).
method_name|other_method_name  // Validator group OR operator, same as ((method_name) OR (other_method_name)).

Examples

Structure

Tag your structures with validate tags as shown below.

type Structure struct {
    Field         string        `validate:"use,tag()|syntax,here(true)"`
    OtherField    int           `validate:"or|use(true)|it(),here"`
    IgnoredField  string        // Just leave the validate tag out if you don't want to validate the field.
    StructField   *OtherStruct  // If not nil, then fields of StructField will also be validated.
}

Real examples

Value int     `validate:"not_empty,max(10)"`                // Value must be between 1 and 10.
Value *int    `validate:"nil|not_empty,max(10)"`            // Value must be nil OR between 1 and 10.
Value string  `validate:"empty,regex(´^[a-z_]*$´),max(64)"` // Value cannot be empty and must contain characters "a-z_" and be less than 64 characters.
Value *string `validate:"not_empty,func"`                   // Value cannot be empty (nil, or empty string) and must pass validation using local validator method ValidateValue().

Clone this wiki locally