# How to add a validation to a command?
PREREQUISITE
Define validation checks as pre-conditions inside the command definition.
With in the command definition, after
input(if any), specify the validations inside apreblock.command <command-name>{ input(...) pre{ condition <conditionName> => <logic> failing "<error-message>" } }Each pre-condition:
- starts with keyword
condition - followed by an appropriate name to the condition being checked. For ex: AmountMustBeGreaterThanZero
- followed by symbol
=> - followed by logic that checks the condition. Use one of the following options:
- Call a domain-logic function. [Recommended]
- Specify the logic as scala code within back-quotes (only encouraged when the logic is simple)
- followed by the error message that needs to be printed when the condition fails, defined in quotes after the keyword
failing[Optional]
- starts with keyword
For example: To ensure the lottery name is unique & the amount given as input is greater than zero:
command create{
input(lotteryName:String,amount:Int)
pre{
condition NewLotteryName => !(lotteryDomainLogicRef.lotteryNameExists(input.lotteryName)) failing "Lottery Name Already Exists !"
condition AmountMustBeGreaterThanZero => `input.amount > 0`
}
...
}
Note:
Multiple conditions can be composed using and
&, or|, implies->, iff<->operatorsAlso possible to hold some computed properties using
letinside thepreblock.If no error message is specified as part of
failing <error-message>condition name becomes the default error message when the condition fails.You can use paramaters in the error message (String interpolation) using
${x}notation. For ex:... failing "Lottery Name ${input.lotteryName} Already Exists !"In order to call a domain logic function (step 2.4.1), hold the domain-logic as a refernce inside the command set.
command-set Lottery { domain-logic-ref lotteryDomainLogicRef:Lottery command create{ ... } }