validate: github.com/go-openapi/validate Index | Examples | Files | Directories

package validate

import "github.com/go-openapi/validate"

Package validate provides methods to validate a swagger specification, as well as tools to validate data against their schema.

This package follows Swagger 2.0. specification (aka OpenAPI 2.0). Reference can be found here: https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md.

Validating a specification

Validates a spec document (from JSON or YAML) against the JSON schema for swagger, then checks a number of extra rules that can't be expressed in JSON schema.

Entry points:

- Spec()
- NewSpecValidator()
- SpecValidator.Validate()

Reported as errors:

[x] definition can't declare a property that's already defined by one of its ancestors
[x] definition's ancestor can't be a descendant of the same model
[x] path uniqueness: each api path should be non-verbatim (account for path param names) unique per method
[x] each security reference should contain only unique scopes
[x] each security scope in a security definition should be unique
[x] parameters in path must be unique
[x] each path parameter must correspond to a parameter placeholder and vice versa
[x] each referenceable definition must have references
[x] each definition property listed in the required array must be defined in the properties of the model
[x] each parameter should have a unique `name` and `type` combination
[x] each operation should have only 1 parameter of type body
[x] each reference must point to a valid object
[x] every default value that is specified must validate against the schema for that property
[x] items property is required for all schemas/definitions of type `array`
[x] path parameters must be declared a required
[x] headers must not contain $ref
[x] schema and property examples provided must validate against their respective object's schema
[x] examples provided must validate their schema

Reported as warnings:

[x] path parameters should not contain any of [{,},\w]
[x] empty path
[x] unused definitions
[x] unsupported validation of examples on non-JSON media types
[x] examples in response without schema
[x] readOnly properties should not be required

Validating a schema

The schema validation toolkit validates data against JSON-schema-draft 04 schema.

It is tested against the full json-schema-testing-suite (https://github.com/json-schema-org/JSON-Schema-Test-Suite), except for the optional part (bignum, ECMA regexp, ...).

It supports the complete JSON-schema vocabulary, including keywords not supported by Swagger (e.g. additionalItems, ...)

Entry points:

- AgainstSchema()
- ...

Known limitations

With the current version of this package, the following aspects of swagger are not yet supported:

[ ] errors and warnings are not reported with key/line number in spec
[ ] default values and examples on responses only support application/json producer type
[ ] invalid numeric constraints (such as Minimum, etc..) are not checked except for default and example values
[ ] rules for collectionFormat are not implemented
[ ] no validation rule for polymorphism support (discriminator) [not done here]
[ ] valid js ECMA regexp not supported by Go regexp engine are considered invalid
[ ] arbitrary large numbers are not supported: max is math.MaxFloat64

Index

Examples

Package Files

debug.go default_validator.go doc.go example_validator.go formats.go helpers.go object_validator.go options.go result.go rexp.go schema.go schema_messages.go schema_props.go slice_validator.go spec.go spec_messages.go type.go validator.go values.go

Constants

const (
    // ArrayDoesNotAllowAdditionalItemsError when an additionalItems construct is not verified by the array values provided.
    //
    // TODO: should move to package go-openapi/errors
    ArrayDoesNotAllowAdditionalItemsError = "array doesn't allow for additional items"

    // HasDependencyError indicates that a dependencies construct was not verified
    HasDependencyError = "%q has a dependency on %s"

    // InvalidSchemaProvidedError indicates that the schema provided to validate a value cannot be properly compiled
    InvalidSchemaProvidedError = "Invalid schema provided to SchemaValidator: %v"

    // InvalidTypeConversionError indicates that a numerical conversion for the given type could not be carried on
    InvalidTypeConversionError = "invalid type conversion in %s: %v "

    // MustValidateAtLeastOneSchemaError indicates that in a AnyOf construct, none of the schema constraints specified were verified
    MustValidateAtLeastOneSchemaError = "%q must validate at least one schema (anyOf)"

    // MustValidateOnlyOneSchemaError indicates that in a OneOf construct, either none of the schema constraints specified were verified, or several were
    MustValidateOnlyOneSchemaError = "%q must validate one and only one schema (oneOf). %s"

    // MustValidateAllSchemasError indicates that in a AllOf construct, at least one of the schema constraints specified were not verified
    //
    // TODO: punctuation in message
    MustValidateAllSchemasError = "%q must validate all the schemas (allOf)%s"

    // MustNotValidateSchemaError indicates that in a Not construct, the schema constraint specified was verified
    MustNotValidateSchemaError = "%q must not validate the schema (not)"
)

Error messages related to schema validation and returned as results.

const (
    // ArrayRequiresItemsError ...
    ArrayRequiresItemsError = "%s for %q is a collection without an element type (array requires items definition)"

    // ArrayInParamRequiresItemsError ...
    ArrayInParamRequiresItemsError = "param %q for %q is a collection without an element type (array requires item definition)"

    // ArrayInHeaderRequiresItemsError ...
    ArrayInHeaderRequiresItemsError = "header %q for %q is a collection without an element type (array requires items definition)"

    // BothFormDataAndBodyError indicates that an operation specifies both a body and a formData parameter, which is forbidden
    BothFormDataAndBodyError = "operation %q has both formData and body parameters. Only one such In: type may be used for a given operation"

    // CannotResolveRefError when a $ref could not be resolved
    CannotResolveReferenceError = "could not resolve reference in %s to $ref %s: %v"

    // CircularAncestryDefinitionError ...
    CircularAncestryDefinitionError = "definition %q has circular ancestry: %v"

    // DefaultValueDoesNotValidateError results from an invalid default value provided
    DefaultValueDoesNotValidateError = "default value for %s in %s does not validate its schema"

    // DefaultValueItemsDoesNotValidateError results from an invalid default value provided for Items
    DefaultValueItemsDoesNotValidateError = "default value for %s.items in %s does not validate its schema"

    // DefaultValueHeaderDoesNotValidateError results from an invalid default value provided in header
    DefaultValueHeaderDoesNotValidateError = "in operation %q, default value in header %s for %s does not validate its schema"

    // DefaultValueHeaderItemsDoesNotValidateError results from an invalid default value provided in header.items
    DefaultValueHeaderItemsDoesNotValidateError = "in operation %q, default value in header.items %s for %s does not validate its schema"

    // DefaultValueInDoesNotValidateError ...
    DefaultValueInDoesNotValidateError = "in operation %q, default value in %s does not validate its schema"

    // DuplicateParamNameError ...
    DuplicateParamNameError = "duplicate parameter name %q for %q in operation %q"

    // DuplicatePropertiesError ...
    DuplicatePropertiesError = "definition %q contains duplicate properties: %v"

    // ExampleValueDoesNotValidateError results from an invalid example value provided
    ExampleValueDoesNotValidateError = "example value for %s in %s does not validate its schema"

    // ExampleValueItemsDoesNotValidateError results from an invalid example value provided for Items
    ExampleValueItemsDoesNotValidateError = "example value for %s.items in %s does not validate its schema"

    // ExampleValueHeaderDoesNotValidateError results from an invalid example value provided in header
    ExampleValueHeaderDoesNotValidateError = "in operation %q, example value in header %s for %s does not validate its schema"

    // ExampleValueHeaderItemsDoesNotValidateError results from an invalid example value provided in header.items
    ExampleValueHeaderItemsDoesNotValidateError = "in operation %q, example value in header.items %s for %s does not validate its schema"

    // ExampleValueInDoesNotValidateError ...
    ExampleValueInDoesNotValidateError = "in operation %q, example value in %s does not validate its schema"

    // EmptyPathParameterError means that a path parameter was found empty (e.g. "{}")
    EmptyPathParameterError = "%q contains an empty path parameter"

    // InvalidDocumentError states that spec validation only processes spec.Document objects
    InvalidDocumentError = "spec validator can only validate spec.Document objects"

    // InvalidItemsPatternError indicates an Items definition with invalid pattern
    InvalidItemsPatternError = "%s for %q has invalid items pattern: %q"

    // InvalidParameterDefinitionError indicates an error detected on a parameter definition
    InvalidParameterDefinitionError = "invalid definition for parameter %s in %s in operation %q"

    // InvalidParameterDefinitionAsSchemaError indicates an error detected on a parameter definition, which was mistaken with a schema definition.
    // Most likely, this situation is encountered whenever a $ref has been added as a sibling of the parameter definition.
    InvalidParameterDefinitionAsSchemaError = "invalid definition as Schema for parameter %s in %s in operation %q"

    // InvalidPatternError ...
    InvalidPatternError = "pattern %q is invalid in %s"

    // InvalidPatternInError indicates an invalid pattern in a schema or items definition
    InvalidPatternInError = "%s in %s has invalid pattern: %q"

    // InvalidPatternInHeaderError indicates a header definition with an invalid pattern
    InvalidPatternInHeaderError = "in operation %q, header %s for %s has invalid pattern %q: %v"

    // InvalidPatternInParamError ...
    InvalidPatternInParamError = "operation %q has invalid pattern in param %q: %q"

    // InvalidReferenceError indicates that a $ref property could not be resolved
    InvalidReferenceError = "invalid ref %q"

    // InvalidResponseDefinitionAsSchemaError indicates an error detected on a response definition, which was mistaken with a schema definition.
    // Most likely, this situation is encountered whenever a $ref has been added as a sibling of the response definition.
    InvalidResponseDefinitionAsSchemaError = "invalid definition as Schema for response %s in %s"

    // MultipleBodyParamError indicates that an operation specifies multiple parameter with in: body
    MultipleBodyParamError = "operation %q has more than 1 body param: %v"

    // NonUniqueOperationIDError indicates that the same operationId has been specified several times
    NonUniqueOperationIDError = "%q is defined %d times"

    // NoParameterInPathError indicates that a path was found without any parameter
    NoParameterInPathError = "path param %q has no parameter definition"

    // NoValidPathErrorOrWarning indicates that no single path could be validated. If Paths is empty, this message is only a warning.
    NoValidPathErrorOrWarning = "spec has no valid path defined"

    // NoValidResponseError indicates that no valid response description could be found for an operation
    NoValidResponseError = "operation %q has no valid response"

    // PathOverlapError ...
    PathOverlapError = "path %s overlaps with %s"

    // PathParamNotInPathError indicates that a parameter specified with in: path was not found in the path specification
    PathParamNotInPathError = "path param %q is not present in path %q"

    // PathParamNotUniqueError ...
    PathParamNotUniqueError = "params in path %q must be unique: %q conflicts with %q"

    // PathParamNotRequiredError ...
    PathParamRequiredError = "in operation %q,path param %q must be declared as required"

    // RefNotAllowedInHeaderError indicates a $ref was found in a header definition, which is not allowed by Swagger
    RefNotAllowedInHeaderError = "IMPORTANT!in %q: $ref are not allowed in headers. In context for header %q%s"

    // RequiredButNotDefinedError ...
    RequiredButNotDefinedError = "%q is present in required but not defined as property in definition %q"

    // SomeParametersBrokenError indicates that some parameters could not be resolved, which might result in partial checks to be carried on
    SomeParametersBrokenError = "some parameters definitions are broken in %q.%s. Cannot carry on full checks on parameters for operation %s"

    // UnresolvedReferencesError indicates that at least one $ref could not be resolved
    UnresolvedReferencesError = "some references could not be resolved in spec. First found: %v"
)

Error messages related to spec validation and returned as results.

const (
    // ExamplesWithoutSchemaWarning indicates that examples are provided for a response,but not schema to validate the example against
    ExamplesWithoutSchemaWarning = "Examples provided without schema in operation %q, %s"

    // ExamplesMimeNotSupportedWarning indicates that examples are provided with a mime type different than application/json, which
    // the validator dos not support yetl
    ExamplesMimeNotSupportedWarning = "No validation attempt for examples for media types other than application/json, in operation %q, %s"

    // PathParamGarbledWarning ...
    PathParamGarbledWarning = "in path %q, param %q contains {,} or white space. Albeit not stricly illegal, this is probably no what you want"

    // PathStrippedParamGarbledWarning ...
    PathStrippedParamGarbledWarning = "path stripped from path parameters %s contains {,} or white space. This is probably no what you want."

    // ReadOnlyAndRequiredWarning ...
    ReadOnlyAndRequiredWarning = "Required property %s in %q should not be marked as both required and readOnly"

    // RefShouldNotHaveSiblingsWarning indicates that a $ref was found with a sibling definition. This results in the $ref taking over its siblings,
    // which is most likely not wanted.
    RefShouldNotHaveSiblingsWarning = "$ref property should have no sibling in %q.%s"

    // RequiredHasDefaultWarning indicates that a required parameter property should not have a default
    RequiredHasDefaultWarning = "%s in %s has a default value and is required as parameter"

    // UnusedDefinitionWarning ...
    UnusedDefinitionWarning = "definition %q is not used anywhere"

    // UnusedParamWarning ...
    UnusedParamWarning = "parameter %q is not used anywhere"

    // UnusedResponseWarning ...
    UnusedResponseWarning = "response %q is not used anywhere"
)

Warning messages related to spec validation and returned as results

const (
    // InternalErrorCode reports an internal technical error
    InternalErrorCode = http.StatusInternalServerError
    // NotFoundErrorCode indicates that a resource (e.g. a $ref) could not be found
    NotFoundErrorCode = http.StatusNotFound
)

Additional error codes

Variables

var (
    // Debug is true when the SWAGGER_DEBUG env var is not empty.
    // It enables a more verbose logging of validators.
    Debug = os.Getenv("SWAGGER_DEBUG") != ""
)

func AgainstSchema Uses

func AgainstSchema(schema *spec.Schema, data interface{}, formats strfmt.Registry) error

AgainstSchema validates the specified data against the provided schema, using a registry of supported formats.

When no pre-parsed *spec.Schema structure is provided, it uses a JSON schema as default. See example.

Code:

// Example using encoding/json as unmarshaller
var schemaJSON = `
{
"properties": {
    "name": {
        "type": "string",
        "pattern": "^[A-Za-z]+$",
        "minLength": 1
    }
	},
"patternProperties": {
	  "address-[0-9]+": {
     "type": "string",
     "pattern": "^[\\s|a-z]+$"
	  }
},
"required": [
    "name"
],
	"additionalProperties": false
}`

schema := new(spec.Schema)
json.Unmarshal([]byte(schemaJSON), schema)

input := map[string]interface{}{}

// JSON data to validate
inputJSON := `{"name": "Ivan","address-1": "sesame street"}`
json.Unmarshal([]byte(inputJSON), &input)

// strfmt.Default is the registry of recognized formats
err := validate.AgainstSchema(schema, input, strfmt.Default)
if err != nil {
    fmt.Printf("JSON does not validate against schema: %v", err)
} else {
    fmt.Printf("OK")
}

Output:

OK

func Enum Uses

func Enum(path, in string, data interface{}, enum interface{}) *errors.Validation

Enum validates if the data is a member of the enum

func FormatOf Uses

func FormatOf(path, in, format, data string, registry strfmt.Registry) *errors.Validation

FormatOf validates if a string matches a format in the format registry

func IsValueValidAgainstRange Uses

func IsValueValidAgainstRange(val interface{}, typeName, format, prefix, path string) error

IsValueValidAgainstRange checks that a numeric value is compatible with the range defined by Type and Format, that is, may be converted without loss.

NOTE: this check is about type capacity and not formal verification such as: 1.0 != 1L

func MaxItems Uses

func MaxItems(path, in string, size, max int64) *errors.Validation

MaxItems validates that there are at most n items in a slice

func MaxLength Uses

func MaxLength(path, in, data string, maxLength int64) *errors.Validation

MaxLength validates a string for maximum length

func Maximum Uses

func Maximum(path, in string, data, max float64, exclusive bool) *errors.Validation

Maximum validates if a number is smaller than a given maximum

func MaximumInt Uses

func MaximumInt(path, in string, data, max int64, exclusive bool) *errors.Validation

MaximumInt validates if a number is smaller than a given maximum

func MaximumNativeType Uses

func MaximumNativeType(path, in string, val interface{}, max float64, exclusive bool) *errors.Validation

MaximumNativeType provides native type constraint validation as a facade to various numeric types versions of Maximum constraint check.

Assumes that any possible loss conversion during conversion has been checked beforehand.

NOTE: currently, the max value is marshalled as a float64, no matter what, which means there may be a loss during conversions (e.g. for very large integers)

TODO: Normally, a JSON MAX_SAFE_INTEGER check would ensure conversion remains loss-free

func MaximumUint Uses

func MaximumUint(path, in string, data, max uint64, exclusive bool) *errors.Validation

MaximumUint validates if a number is smaller than a given maximum

func MinItems Uses

func MinItems(path, in string, size, min int64) *errors.Validation

MinItems validates that there are at least n items in a slice

func MinLength Uses

func MinLength(path, in, data string, minLength int64) *errors.Validation

MinLength validates a string for minimum length

func Minimum Uses

func Minimum(path, in string, data, min float64, exclusive bool) *errors.Validation

Minimum validates if a number is smaller than a given minimum

func MinimumInt Uses

func MinimumInt(path, in string, data, min int64, exclusive bool) *errors.Validation

MinimumInt validates if a number is smaller than a given minimum

func MinimumNativeType Uses

func MinimumNativeType(path, in string, val interface{}, min float64, exclusive bool) *errors.Validation

MinimumNativeType provides native type constraint validation as a facade to various numeric types versions of Minimum constraint check.

Assumes that any possible loss conversion during conversion has been checked beforehand.

NOTE: currently, the min value is marshalled as a float64, no matter what, which means there may be a loss during conversions (e.g. for very large integers)

TODO: Normally, a JSON MAX_SAFE_INTEGER check would ensure conversion remains loss-free

func MinimumUint Uses

func MinimumUint(path, in string, data, min uint64, exclusive bool) *errors.Validation

MinimumUint validates if a number is smaller than a given minimum

func MultipleOf Uses

func MultipleOf(path, in string, data, factor float64) *errors.Validation

MultipleOf validates if the provided number is a multiple of the factor

func MultipleOfInt Uses

func MultipleOfInt(path, in string, data int64, factor int64) *errors.Validation

MultipleOfInt validates if the provided integer is a multiple of the factor

func MultipleOfNativeType Uses

func MultipleOfNativeType(path, in string, val interface{}, multipleOf float64) *errors.Validation

MultipleOfNativeType provides native type constraint validation as a facade to various numeric types version of MultipleOf constraint check.

Assumes that any possible loss conversion during conversion has been checked beforehand.

NOTE: currently, the multipleOf factor is marshalled as a float64, no matter what, which means there may be a loss during conversions (e.g. for very large integers)

TODO: Normally, a JSON MAX_SAFE_INTEGER check would ensure conversion remains loss-free

func MultipleOfUint Uses

func MultipleOfUint(path, in string, data, factor uint64) *errors.Validation

MultipleOfUint validates if the provided unsigned integer is a multiple of the factor

func Pattern Uses

func Pattern(path, in, data, pattern string) *errors.Validation

Pattern validates a string against a regular expression

func Required Uses

func Required(path, in string, data interface{}) *errors.Validation

Required validates an interface for requiredness

func RequiredNumber Uses

func RequiredNumber(path, in string, data float64) *errors.Validation

RequiredNumber validates a number for requiredness

func RequiredString Uses

func RequiredString(path, in, data string) *errors.Validation

RequiredString validates a string for requiredness

func SetContinueOnErrors Uses

func SetContinueOnErrors(c bool)

SetContinueOnErrors sets global default behavior regarding spec validation errors reporting.

For extended error reporting, you most likely want to set it to true. For faster validation, it's better to give up early when a spec is detected as invalid: set it to false (this is the default).

Setting this mode does NOT affect the validation status.

NOTE: this method affects global defaults. It is not suitable for a concurrent usage.

func Spec Uses

func Spec(doc *loads.Document, formats strfmt.Registry) error

Spec validates an OpenAPI 2.0 specification document.

Returns an error flattening in a single standard error, all validation messages.

- TODO: $ref should not have siblings
- TODO: make sure documentation reflects all checks and warnings
- TODO: check on discriminators
- TODO: explicit message on unsupported keywords (better than "forbidden property"...)
- TODO: full list of unresolved refs
- TODO: validate numeric constraints (issue#581): this should be handled like defaults and examples
- TODO: option to determine if we validate for go-swagger or in a more general context
- TODO: check on required properties to support anyOf, allOf, oneOf

NOTE: SecurityScopes are maps: no need to check uniqueness

Code:

// Example with high level spec validation call, without showing warnings

// Example with spec file in this repo:
path := "fixtures/validation/valid-ref.json"
doc, err := loads.Spec(path)
if err == nil {
    validate.SetContinueOnErrors(true)         // Set global options
    errs := validate.Spec(doc, strfmt.Default) // Validates spec with default Swagger 2.0 format definitions

    if errs == nil {
        fmt.Println("This spec is valid")
    } else {
        fmt.Printf("This spec has some validation errors: %v\n", errs)
    }
} else {
    fmt.Println("Could not load this spec")
}

Output:

This spec is valid

Code:

// Example with high level spec validation call, without showing warnings

// Example with online spec URL:
url := "http://petstore.swagger.io/v2/swagger.json"
doc, err := loads.JSONSpec(url)
if err == nil {
    validate.SetContinueOnErrors(true)         // Set global options
    errs := validate.Spec(doc, strfmt.Default) // Validates spec with default Swagger 2.0 format definitions

    if errs == nil {
        fmt.Println("This spec is valid")
    } else {
        fmt.Printf("This spec has some validation errors: %v\n", errs)
    }
} else {
    fmt.Println("Could not load this spec")
}

func UniqueItems Uses

func UniqueItems(path, in string, data interface{}) *errors.Validation

UniqueItems validates that the provided slice has unique elements

type EntityValidator Uses

type EntityValidator interface {
    Validate(interface{}) *Result
}

An EntityValidator is an interface for things that can validate entities

type FieldKey Uses

type FieldKey struct {
    // contains filtered or unexported fields
}

FieldKey is a pair of an object and a field, usable as a key for a map.

func NewFieldKey Uses

func NewFieldKey(obj map[string]interface{}, field string) FieldKey

NewFieldKey returns a pair of an object and field usable as a key of a map.

func (*FieldKey) Field Uses

func (fk *FieldKey) Field() string

Field returns the underlying field of this key.

func (*FieldKey) Object Uses

func (fk *FieldKey) Object() map[string]interface{}

Object returns the underlying object of this key.

type HeaderValidator Uses

type HeaderValidator struct {
    KnownFormats strfmt.Registry
    // contains filtered or unexported fields
}

A HeaderValidator has very limited subset of validations to apply

func NewHeaderValidator Uses

func NewHeaderValidator(name string, header *spec.Header, formats strfmt.Registry) *HeaderValidator

NewHeaderValidator creates a new header validator object

func (*HeaderValidator) Validate Uses

func (p *HeaderValidator) Validate(data interface{}) *Result

Validate the value of the header against its schema

type ItemKey Uses

type ItemKey struct {
    // contains filtered or unexported fields
}

ItemKey is a pair of a slice and an index, usable as a key for a map.

func NewItemKey Uses

func NewItemKey(slice interface{}, i int) ItemKey

NewItemKey returns a pair of a slice and index usable as a key of a map.

func (*ItemKey) Index Uses

func (ik *ItemKey) Index() int

Index returns the underlying index of this key.

func (*ItemKey) Slice Uses

func (ik *ItemKey) Slice() []interface{}

Slice returns the underlying slice of this key.

type Opts Uses

type Opts struct {
    ContinueOnErrors bool // true: continue reporting errors, even if spec is invalid
}

Opts specifies validation options for a SpecValidator.

NOTE: other options might be needed, for example a go-swagger specific mode.

type ParamValidator Uses

type ParamValidator struct {
    KnownFormats strfmt.Registry
    // contains filtered or unexported fields
}

A ParamValidator has very limited subset of validations to apply

func NewParamValidator Uses

func NewParamValidator(param *spec.Parameter, formats strfmt.Registry) *ParamValidator

NewParamValidator creates a new param validator object

func (*ParamValidator) Validate Uses

func (p *ParamValidator) Validate(data interface{}) *Result

Validate the data against the description of the parameter

type Result Uses

type Result struct {
    Errors     []error
    Warnings   []error
    MatchCount int
    // contains filtered or unexported fields
}

Result represents a validation result set, composed of errors and warnings.

It is used to keep track of all detected errors and warnings during the validation of a specification.

Matchcount is used to determine which errors are relevant in the case of AnyOf, OneOf schema validation. Results from the validation branch with most matches get eventually selected.

TODO: keep path of key originating the error

func (*Result) AddErrors Uses

func (r *Result) AddErrors(errors ...error)

AddErrors adds errors to this validation result (if not already reported).

Since the same check may be passed several times while exploring the spec structure (via $ref, ...) reported messages are kept unique.

func (*Result) AddWarnings Uses

func (r *Result) AddWarnings(warnings ...error)

AddWarnings adds warnings to this validation result (if not already reported).

func (*Result) AsError Uses

func (r *Result) AsError() error

AsError renders this result as an error interface

TODO: reporting / pretty print with path ordered and indented

func (*Result) Data Uses

func (r *Result) Data() interface{}

Data returns the original data object used for validation. Mutating this renders the result invalid.

func (*Result) FieldSchemata Uses

func (r *Result) FieldSchemata() map[FieldKey][]*spec.Schema

FieldSchemata returns the schemata which apply to fields in objects.

func (*Result) HasErrors Uses

func (r *Result) HasErrors() bool

HasErrors returns true when this result is invalid.

Returns false on a nil *Result.

func (*Result) HasErrorsOrWarnings Uses

func (r *Result) HasErrorsOrWarnings() bool

HasErrorsOrWarnings returns true when this result contains either errors or warnings.

Returns false on a nil *Result.

func (*Result) HasWarnings Uses

func (r *Result) HasWarnings() bool

HasWarnings returns true when this result contains warnings.

Returns false on a nil *Result.

func (*Result) Inc Uses

func (r *Result) Inc()

Inc increments the match count

func (*Result) IsValid Uses

func (r *Result) IsValid() bool

IsValid returns true when this result is valid.

Returns true on a nil *Result.

func (*Result) ItemSchemata Uses

func (r *Result) ItemSchemata() map[ItemKey][]*spec.Schema

ItemSchemata returns the schemata which apply to items in slices.

func (*Result) Merge Uses

func (r *Result) Merge(others ...*Result) *Result

Merge merges this result with the other one(s), preserving match counts etc.

func (*Result) MergeAsErrors Uses

func (r *Result) MergeAsErrors(others ...*Result) *Result

MergeAsErrors merges this result with the other one(s), preserving match counts etc.

Warnings from input are merged as Errors in the returned merged Result.

func (*Result) MergeAsWarnings Uses

func (r *Result) MergeAsWarnings(others ...*Result) *Result

MergeAsWarnings merges this result with the other one(s), preserving match counts etc.

Errors from input are merged as Warnings in the returned merged Result.

func (*Result) RootObjectSchemata Uses

func (r *Result) RootObjectSchemata() []*spec.Schema

RootObjectSchemata returns the schemata which apply to the root object.

type SchemaValidator Uses

type SchemaValidator struct {
    Path string

    Schema *spec.Schema

    Root         interface{}
    KnownFormats strfmt.Registry
    // contains filtered or unexported fields
}

SchemaValidator validates data against a JSON schema

func NewSchemaValidator Uses

func NewSchemaValidator(schema *spec.Schema, rootSchema interface{}, root string, formats strfmt.Registry) *SchemaValidator

NewSchemaValidator creates a new schema validator.

Panics if the provided schema is invalid.

func (*SchemaValidator) Applies Uses

func (s *SchemaValidator) Applies(source interface{}, kind reflect.Kind) bool

Applies returns true when this schema validator applies

func (*SchemaValidator) SetPath Uses

func (s *SchemaValidator) SetPath(path string)

SetPath sets the path for this schema valdiator

func (*SchemaValidator) Validate Uses

func (s *SchemaValidator) Validate(data interface{}) *Result

Validate validates the data against the schema

type SpecValidator Uses

type SpecValidator struct {
    KnownFormats strfmt.Registry
    Options      Opts // validation options
    // contains filtered or unexported fields
}

SpecValidator validates a swagger 2.0 spec

func NewSpecValidator Uses

func NewSpecValidator(schema *spec.Schema, formats strfmt.Registry) *SpecValidator

NewSpecValidator creates a new swagger spec validator instance

func (*SpecValidator) SetContinueOnErrors Uses

func (s *SpecValidator) SetContinueOnErrors(c bool)

SetContinueOnErrors sets the ContinueOnErrors option for this validator.

func (*SpecValidator) Validate Uses

func (s *SpecValidator) Validate(data interface{}) (errs *Result, warnings *Result)

Validate validates the swagger spec

Code:

// Example of spec validation call with full result

// Example with online spec URL:
//url := "http://petstore.swagger.io/v2/swagger.json"
//doc, err := loads.JSONSpec(url)

// Example with spec file in this repo:
path := "fixtures/validation/valid-ref.json"
doc, err := loads.Spec(path)
if err == nil {
    validator := validate.NewSpecValidator(doc.Schema(), strfmt.Default)
    validator.SetContinueOnErrors(true)  // Set option for this validator
    result, _ := validator.Validate(doc) // Validates spec with default Swagger 2.0 format definitions
    if result.IsValid() {
        fmt.Println("This spec is valid")
    } else {
        fmt.Println("This spec has some validation errors")
    }
    if result.HasWarnings() {
        fmt.Println("This spec has some validation warnings")
    }
}

Output:

This spec is valid
This spec has some validation warnings

Code:

// Example of spec validation call with full result

// Example with online spec URL:
url := "http://petstore.swagger.io/v2/swagger.json"
doc, err := loads.JSONSpec(url)
if err == nil {
    validator := validate.NewSpecValidator(doc.Schema(), strfmt.Default)
    validator.SetContinueOnErrors(true)  // Set option for this validator
    result, _ := validator.Validate(doc) // Validates spec with default Swagger 2.0 format definitions
    if result.IsValid() {
        fmt.Println("This spec is valid")
    } else {
        fmt.Println("This spec has some validation errors")
    }
    if result.HasWarnings() {
        fmt.Println("This spec has some validation warnings")
    }
}

Bugs

This section should move to a part dedicated to spec validation as it will conflict with regular schemas where a property "headers" is defined.

succeededOnce is always false

can't get to here. Should remove dead code (commented out).

Directories

PathSynopsis
post

Package validate imports 23 packages (graph) and is imported by 220 packages. Updated 2018-10-07. Refresh now. Tools for package owners.