package dsl
Provides a DSL for defining validation rules.
Overview
Accord provides a convenient DSL for defining validation rules. To define a validator over some type T
,
import this package and invoke validator[T]. You can then use the
provided sample object to define various rules:
scala> case class Person( name: String, age: Int ) defined class Person scala> import com.wix.accord.dsl._ // Import the validator DSL import com.wix.accord.dsl._ scala> implicit val personValidator = validator[ Person ] { p => | // Validation rules: | p.name is notEmpty | p.age should be >= 18 | } personValidator: com.wix.accord.transform.ValidationTransform.TransformedValidator[Person] = <function1>
Accord adds an implicit logical and
relation between the rules, so all rules must apply in order
for the validation to be successful. You can specify as many rules as you like.
Descriptions
Each validation rule has an associated description (accessible via com.wix.accord.Violation.description). This description is automatically generated by Accord:
scala> import com.wix.accord._ import com.wix.accord._ scala> validate( Person( "", 15 ) ) res1: com.wix.accord.Result = Failure(Set(RuleViolation(,must not be empty,Some(name)), RuleViolation(15,got 15, expected 18 or more,Some(age))))
You can also explicitly provide a description with the "as" modifier:
scala> implicit val personValidator = validator[ Person ] { p => | p.name as "Full name" is notEmpty | p.age as "Age" should be >= 18 | } personValidator: com.wix.accord.transform.ValidationTransform.TransformedValidator[Person] = <function1> scala> validate( Person( "", 15 ) ) res2: com.wix.accord.Result = Failure(Set(RuleViolation(,must not be empty,Some(Full name)), RuleViolation(15,got 15, expected 18 or more,Some(Age))))
Combinators
Accord offers a built-in library of building blocks (called "combinators") that can be composed into more complex validation rules:
General-purpose
// Equality sample.field is equalTo( "value" ) sample.field is notEqualTo( "value" ) // Nullability (only applies to reference types) sample.field is aNull sample.field is notNull // Delegation sample.field is valid // Implicitly, or sample.field is valid( myOwnValidator ) // Explicitly
Primitives
// Booleans sample.booleanField is true sample.booleanField is false // Strings sample.stringField should startWith( "prefix" ) sample.stringField should endWith( "suffix" ) sample.stringField should matchRegex( "b[aeiou]t" ) // Matches "bat" and "dingbat" sample.stringField should matchRegexFully( "b[aeiou]t" ) // Matches "bat" but not "dingbat" sample.stringField should matchRegex( pattern ) // You can also use java.util.regex.Pattern sample.stringField should matchRegex( regex ) // ... or scala.util.matching.Regex sample.stringField is blank // Matches empty or whitespace-only strings sample.stringField is notBlank // You can use "must" instead of "should": sample.stringField must startWith( "prefix" ) // Strings are also "collection-like", so all collection combinators apply (see below) sample.stringField is notEmpty // Numerics (applies to any type with an instance of scala.math.Ordering in implicit search scope): sample.intField should be < 5 sample.intField should be > 5 sample.intField should be <= 5 sample.intField should be >= 5 sample.intField should be == 5 sample.intField is between( 0, 10 ) sample.intField is between( 0, 10 ).exclusive sample.intField is within( 0 to 10 ) // Inclusive sample.intField is within( 0 until 10 ) // Exclusive
Collections
// Emptiness sample.seq is empty sample.seq is notEmpty // This applies to any type that has a boolean "isEmpty" property, such as string) // The "each" modifier applies the validation to all members of a collection: sample.seq.each should be >= 10 sample.option.each should be >= 10 // Allows None or Some(15) // Size (applies to any type with an integer "size" property) // See "Numerics" above for additional operations sample.seq has size >= 8 sample.entities have size >= 8 // You can use "have" in place of "has"
Boolean Expressions
// Logical AND (not strictly required, since you can just split into separate rules) ( person.name is notEmpty ) and ( person.age should be >= 18 ) // Logical OR ( person.email is notEmpty ) or ( person.phoneNumber is notEmpty ) // You can also nest rules: ( fromJava.tags is aNull ) or ( ( fromJava.tags is notEmpty ) and ( fromJava.tags.each should matchRegexFully( "\\S+" ) ) )
- Alphabetic
- By Inheritance
- dsl
- BooleanOps
- OrderingOps
- GenericOps
- CollectionOps
- StringOps
- AnyRef
- Any
- Hide All
- Show All
- Public
- All
Type Members
-
trait
BooleanOps extends AnyRef
Provides a DSL for booleans.
-
implicit
class
ValidatorBooleanOps[T] extends AnyRef
Extends validators with useful helpers.
Extends validators with useful helpers.
- Definition Classes
- BooleanOps
- class CollectionDslContext[Inner, Outer] extends ContextTransformer[Inner, Outer]
-
trait
CollectionOps extends AnyRef
Provides a DSL for collection-like objects.
Provides a DSL for collection-like objects. Works in conjunction with com.wix.accord.dsl.DslContext.
- trait ContextTransformer[Inner, Outer] extends AnyRef
-
implicit
class
Contextualizer[U] extends SimpleDslContext[U]
Wraps expressions under validation with the Accord DSL.
Wraps expressions under validation with the Accord DSL.
This class provides the entry point into the DSL, by wrapping an expression with a specialized scope (this is later used during the macro transform). This enables syntax such as
p.firstName is notEmpty
, wherep.firstName
is the actual expression under validation.See the package documentation for a full description of the DSL.
- U
The type of the provided expression.
- See also
com.wix.accord.dsl
-
implicit
class
Descriptor[U] extends AnyRef
Enables explicitly describing expression under validation.
Enables explicitly describing expression under validation.
After the macro transform, the resulting validator will use the specified description to render violations. See the as method for full example.
- U
The type of the provided expression.
- See also
com.wix.accord.dsl
- trait DslContext[Inner, Outer] extends AnyRef
- trait FallbackIndexDescriptions extends AnyRef
-
trait
GenericOps extends AnyRef
Provides a DSL for untyped validators.
-
type
HasSize = Any { def size: Int }
A structural type representing any object that has a size.
A structural type representing any object that has a size.
- Definition Classes
- CollectionOps
- trait IndexedDescriptions[T] extends AnyRef
-
trait
OrderingOps extends AnyRef
Provides a DSL for types with a corresponding implmentation of scala.math.Ordering.
Provides a DSL for types with a corresponding implmentation of scala.math.Ordering.
Implementation note: All methods here should only require scala.math.PartialOrdering, but the canonical implicits are defined in the Ordering companion and would therefore not be imported by default at the call site. This seems like a worthwhile trade-off.
- trait SimpleDslContext[U] extends DslContext[U, U] with ContextTransformer[U, U]
-
trait
StringOps extends AnyRef
Provides a DSL for string validators.
Value Members
-
def
<[T](other: T)(implicit arg0: Ordering[T], arg1: Nullability[T]): combinators.LesserThan[T]
Generates a validator that succeeds only if the provided value is less than the specified bound.
Generates a validator that succeeds only if the provided value is less than the specified bound.
- Definition Classes
- OrderingOps
-
def
<=[T](other: T)(implicit arg0: Ordering[T], arg1: Nullability[T]): combinators.LesserThanOrEqual[T]
Generates a validator that succeeds if the provided value is less than or equal to the specified bound.
Generates a validator that succeeds if the provided value is less than or equal to the specified bound.
- Definition Classes
- OrderingOps
-
def
==[T](other: T)(implicit arg0: Ordering[T], arg1: Nullability[T]): combinators.EquivalentTo[T]
Generates a validator that succeeds if the provided value is exactly equal to the specified value.
Generates a validator that succeeds if the provided value is exactly equal to the specified value.
- Definition Classes
- OrderingOps
-
def
>[T](other: T)(implicit arg0: Ordering[T], arg1: Nullability[T]): combinators.GreaterThan[T]
Generates a validator that succeeds only if the provided value is greater than the specified bound.
Generates a validator that succeeds only if the provided value is greater than the specified bound.
- Definition Classes
- OrderingOps
-
def
>=[T](other: T)(implicit arg0: Ordering[T], arg1: Nullability[T]): combinators.GreaterThanOrEqual[T]
Generates a validator that succeeds if the provided value is greater than or equal to the specified bound.
Generates a validator that succeeds if the provided value is greater than or equal to the specified bound.
- Definition Classes
- OrderingOps
-
def
aNull: Validator[AnyRef]
Specifies a validator that succeeds only if the validation expression is null.
Specifies a validator that succeeds only if the validation expression is null.
- Definition Classes
- GenericOps
-
def
anInstanceOf[T <: AnyRef](implicit arg0: ClassTag[T]): Validator[AnyRef]
Specifies a validator that succeeds only if the validation expression evaluates to the specified type.
Specifies a validator that succeeds only if the validation expression evaluates to the specified type. Respects nulls.
- Definition Classes
- GenericOps
-
val
be: OrderingOps
Provides the "be" keyword.
Provides the "be" keyword.
Makes all members of OrderingOps accessible via the following syntax:
p.age should be > 5`
- See also
com.wix.accord.dsl.OrderingOps
-
def
between[T](lowerBound: T, upperBound: T)(implicit arg0: Ordering[T], arg1: Nullability[T]): combinators.InRangeInclusive[T]
Generates a validator that succeeds if the provided value is between (inclusive) the specified bounds.
Generates a validator that succeeds if the provided value is between (inclusive) the specified bounds. The method
exclusive
is provided to specify an exclusive upper bound.- Definition Classes
- OrderingOps
-
def
blank: Validator[String]
Specifies a validator that operates on strings and succeeds only if the validation expression is blank (i.e.
Specifies a validator that operates on strings and succeeds only if the validation expression is blank (i.e. empty or whitespace-only).
- Definition Classes
- StringOps
-
implicit
def
booleanToBooleanValidator(b: Boolean): Validator[Boolean]
An implicit conversion from boolean to a respective
IsTrue
/IsFalse
instance; this enables syntax such ascustomer.emailOptIn is true
.An implicit conversion from boolean to a respective
IsTrue
/IsFalse
instance; this enables syntax such ascustomer.emailOptIn is true
.- Definition Classes
- BooleanOps
-
def
distinct: combinators.Distinct.type
Specifies a validator that fails on collections with duplicate elements.
Specifies a validator that fails on collections with duplicate elements.
- Definition Classes
- CollectionOps
-
def
empty[T <: AnyRef](implicit ev: (T) ⇒ combinators.HasEmpty): Validator[T]
Specifies a validator that succeeds on empty instances; the object under validation must implement
def isEmpty: Boolean
(see com.wix.accord.combinators.HasEmpty).Specifies a validator that succeeds on empty instances; the object under validation must implement
def isEmpty: Boolean
(see com.wix.accord.combinators.HasEmpty).- Definition Classes
- CollectionOps
-
def
endWith(suffix: String): Validator[String]
Specifies a validator that operates on strings and succeeds only if the validation expression ends with the specified suffix.
Specifies a validator that operates on strings and succeeds only if the validation expression ends with the specified suffix.
- Definition Classes
- StringOps
-
def
equalTo[T](to: T): Validator[T]
Specifies a validator that succeeds only if the validation expression is equal to the specified value.
Specifies a validator that succeeds only if the validation expression is equal to the specified value. Respects nulls an performs equality checks via java.lang.Object.equals.
- Definition Classes
- GenericOps
-
implicit
def
genericTraversableOnce2HasSize[T](gto: T)(implicit ev: (T) ⇒ GenTraversableOnce[_]): HasSize
An implicit conversion to enable any collection-like object (e.g.
An implicit conversion to enable any collection-like object (e.g. strings, options) to be handled by com.wix.accord.dsl.CollectionDslContext.
java.lang.String does not directly implement
size
(in practice it is implemented in scala.collection.IndexedSeqOptimized via an implicit conversion and an inheritance stack), and this is a case where the Scala compiler does not always infer structural types correctly. By requiring a view bound fromT
to scala.collection.GenTraversableOnce we can force any collection-like structure to conform to the structural type com.wix.accord.dsl.CollectionOps.HasSize, and by requiring a view bound fromT
to com.wix.accord.dsl.CollectionOps.HasSize at the call site (via com.wix.accord.dsl.CollectionDslContext) we additionally support any class that directly conforms to the structural type as well.- T
The type that conforms, directly or implicitly, to com.wix.accord.dsl.CollectionOps.HasSize.
- gto
An object that is, or is implicitly convertible to, scala.collection.GenTraversableOnce.
- returns
The specified object, strictly-typed as com.wix.accord.dsl.CollectionOps.HasSize.
- Definition Classes
- CollectionOps
-
def
in[T](items: T*): Validator[T]
Specifies a validator that succeeds only if the object exists in the specified set of items.
Specifies a validator that succeeds only if the object exists in the specified set of items.
- Definition Classes
- CollectionOps
-
def
in[T](set: Set[T]): Validator[T]
Specifies a validator that succeeds only if the object exists in the specified set.
Specifies a validator that succeeds only if the object exists in the specified set.
- Definition Classes
- CollectionOps
-
def
matchRegex(pattern: Pattern): Validator[String]
Specifies a validator that operates on strings and succeeds only if the validation expression matches the specified regular expression.
Specifies a validator that operates on strings and succeeds only if the validation expression matches the specified regular expression.
- Definition Classes
- StringOps
-
def
matchRegex(regex: Regex): Validator[String]
Specifies a validator that operates on strings and succeeds only if the validation expression matches the specified regular expression.
Specifies a validator that operates on strings and succeeds only if the validation expression matches the specified regular expression.
- Definition Classes
- StringOps
-
def
matchRegex(regex: String): Validator[String]
Specifies a validator that operates on strings and succeeds only if the validation expression matches the specified regular expression.
Specifies a validator that operates on strings and succeeds only if the validation expression matches the specified regular expression.
- Definition Classes
- StringOps
-
def
matchRegexFully(pattern: Pattern): Validator[String]
Specifies a validator that operates on strings and succeeds only if the validation expression **fully** matches the specified regular expression.
Specifies a validator that operates on strings and succeeds only if the validation expression **fully** matches the specified regular expression. See com.wix.accord.combinators.StringCombinators.MatchesRegex for a full explanation of the difference between partial and full matching.
- Definition Classes
- StringOps
-
def
matchRegexFully(regex: Regex): Validator[String]
Specifies a validator that operates on strings and succeeds only if the validation expression **fully** matches the specified regular expression.
Specifies a validator that operates on strings and succeeds only if the validation expression **fully** matches the specified regular expression. See com.wix.accord.combinators.StringCombinators.MatchesRegex for a full explanation of the difference between partial and full matching.
- Definition Classes
- StringOps
-
def
matchRegexFully(regex: String): Validator[String]
Specifies a validator that operates on strings and succeeds only if the validation expression **fully** matches the specified regular expression.
Specifies a validator that operates on strings and succeeds only if the validation expression **fully** matches the specified regular expression. See com.wix.accord.combinators.StringCombinators.MatchesRegex for a full explanation of the difference between partial and full matching.
- Definition Classes
- StringOps
-
def
notAnInstanceOf[T <: AnyRef](implicit arg0: ClassTag[T]): Validator[AnyRef]
Specifies a validator that fails only if the validation expression evaluates to the specified type.
Specifies a validator that fails only if the validation expression evaluates to the specified type. Respects nulls.
- Definition Classes
- GenericOps
-
def
notBlank: Validator[String]
Specifies a validator that operates on strings and succeeds only if the validation expression is not blank (i.e.
Specifies a validator that operates on strings and succeeds only if the validation expression is not blank (i.e. empty or whitespace-only).
- Definition Classes
- StringOps
-
def
notEmpty[T <: AnyRef](implicit ev: (T) ⇒ combinators.HasEmpty): Validator[T]
Specifies a validator that fails on empty instances; the object under validation must implement
def isEmpty: Boolean
(see com.wix.accord.combinators.HasEmpty).Specifies a validator that fails on empty instances; the object under validation must implement
def isEmpty: Boolean
(see com.wix.accord.combinators.HasEmpty).- Definition Classes
- CollectionOps
-
def
notEqualTo[T](to: T): Validator[T]
Specifies a validator that succeeds only if the validation expression is not equal to the specified value.
Specifies a validator that succeeds only if the validation expression is not equal to the specified value. Respects nulls an performs equality checks via java.lang.Object.equals.
- Definition Classes
- GenericOps
-
def
notNull: Validator[AnyRef]
Specifies a validator that succeeds only if the validation expression is not null.
Specifies a validator that succeeds only if the validation expression is not null.
- Definition Classes
- GenericOps
-
def
prefix: String
- Attributes
- protected
- Definition Classes
- CollectionOps
-
val
size: OrderingOps
Provides access to size-based validators (where the object under validation must implement
def size: Int
, see com.wix.accord.dsl.CollectionOps.HasSize).Provides access to size-based validators (where the object under validation must implement
def size: Int
, see com.wix.accord.dsl.CollectionOps.HasSize). Enables syntax such asc.students has size > 0
.- Definition Classes
- CollectionOps
-
def
snippet: String
- Attributes
- protected
- Definition Classes
- OrderingOps
-
def
startWith(prefix: String): Validator[String]
Specifies a validator that operates on strings and succeeds only if the validation expression starts with the specified prefix.
Specifies a validator that operates on strings and succeeds only if the validation expression starts with the specified prefix.
- Definition Classes
- StringOps
-
def
valid[T](implicit validator: Validator[T]): Validator[T]
Delegates validation to a pre-defined validation rule, which is encoded as an implicit com.wix.accord.Validator in scope.
Delegates validation to a pre-defined validation rule, which is encoded as an implicit com.wix.accord.Validator in scope. Enables composition of validation rules, as in:
case class Address( address1: String, address2: String, city: String, ... ) case class Item( sku: String, count: Int, ... ) case class Shipment( items: Seq[ Item ], address: Location, ... )
implicit val addressValidator = validator[ Address ] { ... } implicit val itemValidator = validator[ Item ] { ... }
implicit val shipmentValidator = validator[ Shipment ] { shipment => shipment.address is valid // Implicitly uses addressValidator shipment.items.each is valid // Implicitly uses itemValidator }
- Definition Classes
- GenericOps
-
macro
def
validator[T](v: (T) ⇒ Unit): TransformedValidator[T]
Defines a new validator for the specified type.
Defines a new validator for the specified type.
This function takes a block of validation rules (encoded as a "thunk"), and rewrites them as a full-fledged instance of Validator. A full example and details of the available syntax can be found in the package documentation.
Details of the code transformation are documented in ValidationTransform (fair warning: this description is quite low-level and fairly involved, and will likely not be of interest to most users).
- T
The type under validation.
- v
The validation code block; may contain any combination of validation statements.
- returns
The validation code block rewritten as a com.wix.accord.Validator for the specified type
T
.
- See also
com.wix.accord.dsl
-
def
within[T](range: NumericRange[T])(implicit arg0: Ordering[T], arg1: Nullability[T]): combinators.InRange[T]
Generates a validator that succeeds if the provided value is within the specified range.
Generates a validator that succeeds if the provided value is within the specified range.
- Definition Classes
- OrderingOps
-
def
within(range: Range): combinators.InRange[Int]
Generates a validator that succeeds if the provided value is within the specified range.
Generates a validator that succeeds if the provided value is within the specified range.
- Definition Classes
- OrderingOps
- object Aggregates
- object IndexedDescriptions extends FallbackIndexDescriptions