case class SchemaValidator extends Product with Serializable
Allows a JSON Schema to be used to validate a JSON data object.
A validator wraps a Schema along with
the formats
partial function to allows JSON data object to be
validated. The use of a partial function for resolving different
formats allows third party formats to be supported.
An example use is:
val schema = parse(""" { "properties": { "foo": {"type": "integer"}, "bar": {"type": "string"} } }""" ) val validator = Schema(schema).andThen(SchemaValidator(_)) val result = validator.validate(data).isValid
It is also possible to add in extra format
values using a partial
function:
private implicit val bundle = MessagesBundle("com.example.Resources") val formats: PartialFunction[(String, String), Option[Message]] = { case ("phonenumber", value) => "^[0-9]{8}$".r.findFirstIn(value) match { case None => Some(Message("BadPhoneNubmer", value)) case Some(_) => None } } val validator = Schema(schema) .andThen(SchemaValidator(_).withFormats(formats))
A standard set of formats are provided based on the JSON Schema
Draft #7. In order to support formats outside the standard the
withFormats()
method should be provided with a partial function
to cater for extra formats.
- Source
- SchemaValidator.scala
- Alphabetic
- By Inheritance
- SchemaValidator
- Serializable
- Product
- Equals
- AnyRef
- Any
- Hide All
- Show All
- Public
- Protected
Value Members
- final def !=(arg0: Any): Boolean
- Definition Classes
- AnyRef → Any
- final def ##(): Int
- Definition Classes
- AnyRef → Any
- final def ==(arg0: Any): Boolean
- Definition Classes
- AnyRef → Any
- final def asInstanceOf[T0]: T0
- Definition Classes
- Any
- def clone(): AnyRef
- Attributes
- protected[lang]
- Definition Classes
- AnyRef
- Annotations
- @throws(classOf[java.lang.CloneNotSupportedException]) @native()
- final def eq(arg0: AnyRef): Boolean
- Definition Classes
- AnyRef
- def finalize(): Unit
- Attributes
- protected[lang]
- Definition Classes
- AnyRef
- Annotations
- @throws(classOf[java.lang.Throwable])
- val formats: Formats
- final def getClass(): Class[_ <: AnyRef]
- Definition Classes
- AnyRef → Any
- Annotations
- @native()
- final def isInstanceOf[T0]: Boolean
- Definition Classes
- Any
- final def ne(arg0: AnyRef): Boolean
- Definition Classes
- AnyRef
- final def notify(): Unit
- Definition Classes
- AnyRef
- Annotations
- @native()
- final def notifyAll(): Unit
- Definition Classes
- AnyRef
- Annotations
- @native()
- def productElementNames: Iterator[String]
- Definition Classes
- Product
- val schema: Schema
- final def synchronized[T0](arg0: => T0): T0
- Definition Classes
- AnyRef
- def validate(json: JValue, readOnly: Boolean = false): ValidatorResult
Validates a JSON object.
Validates a JSON object.
A JSON object is validated against the schema supplied when the validator was created. If the data validates then a Validated containing a
Valid
Unit
value is returned. If any errors occur a NonEmptyList of Error entries is returned, where each entry describe a single error.JSON Schema supports a
readOnly
property which indicated whether a property can be updated. The second argument (defaulting tofalse
) indicates whether values set onreadOnly
properties should fail.Example:
val schema = parse(""" { "properties": { "foo": {"type": "integer"}, "bar": {"type": "string"} } }""" ) val validator = Schema(schema).andThen(SchemaValidator(_)) val result = validator.validate(data).isValid
- json
data object to be validated
- readOnly
true
if properties nominated asreadOnly
cannot be modified- returns
Validated with valid
Unit
value if data passes validation, otherwise a NonEmptyList of all errors as Error objects
- final def wait(): Unit
- Definition Classes
- AnyRef
- Annotations
- @throws(classOf[java.lang.InterruptedException])
- final def wait(arg0: Long, arg1: Int): Unit
- Definition Classes
- AnyRef
- Annotations
- @throws(classOf[java.lang.InterruptedException])
- final def wait(arg0: Long): Unit
- Definition Classes
- AnyRef
- Annotations
- @throws(classOf[java.lang.InterruptedException]) @native()
- def withFormats(pf: Formats): SchemaValidator
Provide extra parsing for
format
string values.Provide extra parsing for
format
string values.JSON Schema allows a
format
to be specified for string based values, where the format defines the type of value stored in the string (e.g. date, time, email, etc). The JSON Schema Draft #7 standard specifies a number of formats that should be provided. Most of these formats are supported by the validator.It is possible to extend the formats supported by providing a partial function containing format handlers. The partial function takes a tuple of two strings as input. The first string in the name of the format found and the second is the value in the JSON data. The return value is an Option containing a Message. If the value passes validation then a scala.None value should be returned, otherwise a message containing a suitable error string wrapped in a Some should be returned.
Example:
private implicit val bundle = MessagesBundle("com.example.Resources") val formats: PartialFunction[(String, String), Option[Message]] = { case ("phonenumber", value) => "^[0-9]{8}$".r.findFirstIn(value) match { case None => Some(Message("BadPhoneNubmer", value)) case Some(_) => None } } val validator = Schema(schema) .andThen(SchemaValidator(_).withFormats(formats)) val valid = validator.validate(parse("""{"phone": "90914536"}""")).isValid
The
withFormats()
method may be called a number of times to add in a variety of formats. Each call adds the partial function to the start of the chain, allowing earlier definitions to be overridden.- pf
partial function to validate JSON Schema
format
settings- returns
SchemaValidator incorporating formats partial function
Documentation for the Axiell Schema Project
Overview
The Axiell Schema Project provides a small library for validating JSON documents against a JSON Schema. The library conforms to the JSON Schema Draft #7 specification.
The library is based on a few simple principles, namely:
Package structure
The
packages consists of a number of utilities, where each utility provides a single piece of functionality. Since the library validates JSON structures two main components are provided. The first component (com.axiell.schema
) allows JSON documents conforming to the JSON Schema specification to be read. Once read a resolution process may be required to resolve any external references defined in the document.com.axiell.schema.Schema
The second component (
) takes a resolved schema and allows JSON documents to be validated against that schema. When creating a validator it is also possible to incorporate your own "format" types for validation.com.axiell.schema.SchemaValidator
A set of auxiliary components implement parsers for many of the "format" types and can be used independently of the validator itself.
Notable utilities are:
Schema
wrapper around a JSON document containing the document itself, its$id
value and resolution mappings for all$id
and$ref
directives.SchemaValidator
takes aSchema
and an optional handler for "format" types and provides a validation method for arbitrary JSON documents.Implicits
implements implicit methods and classes used to convert one class to another or pimp methods onto existing classes (e.g.same()
method toJValue
class).EmailAddress
Hostname
Ipv4Address
Ipv6Address
JsonPointer
RelativeJsonPointer
Dependencies
The list of dependencies are:
Axiell Util Library
provides error handling classes and methods that allow multilingual error messages to be generated.JSON for Scala Library
provides mthods for dealing with JSON structures. The routines work around an AST (Abstract Syntax Tree) used to represent a JSON document.Cats Functional Programming Library
provides various traits, classes and methods that simplify functional programming in Scala. Also provides theValidated
class used to return lists of validation errors.