# How to add a validation to a command?

PREREQUISITE


Define validation checks as pre-conditions inside the command definition.

  1. With in the command definition, after input (if any), specify the validations inside a pre block.



     




    command <command-name>{
    		input(...)
    		pre{
    			condition <conditionName> => <logic> failing "<error-message>"
    		}
    }
    
  2. Each pre-condition:

    1. starts with keyword condition
    2. followed by an appropriate name to the condition being checked. For ex: AmountMustBeGreaterThanZero
    3. followed by symbol =>
    4. followed by logic that checks the condition. Use one of the following options:
      1. Call a domain-logic function. [Recommended]
      2. Specify the logic as scala code within back-quotes (only encouraged when the logic is simple)
    5. followed by the error message that needs to be printed when the condition fails, defined in quotes after the keyword failing [Optional]

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 <-> operators

  • Also possible to hold some computed properties using let inside the pre block.

  • 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{ ... }
    }