(error-messages-for "" ["Please enter a name" not-empty])
; => ("Please enter a name")
diff --git a/content/cftbat/writing-macros.html b/content/cftbat/writing-macros.html index 469dbac2..94474ebb 100644 --- a/content/cftbat/writing-macros.html +++ b/content/cftbat/writing-macros.html @@ -519,7 +519,7 @@
The first argument, to-validate
, is the field you want to validate. The second argument, message-validator-pairs
, should be a seq with an even number of elements. This seq gets grouped into pairs with (partition 2 message-validator-pairs)
. The first element of the pair should be an error message, and the second element of the pair should be a function (just like the pairs are arranged in order-details-validation
). The error-messages-for
function works by filtering out all error message and validation pairs where the validation function returns true
when applied to to-validate
. It then uses map first
to get the first element of each pair, the error message. Here it is in action:
The first argument, to-validate
, is the field you want to validate. The second argument, message-validator-pairs
, should be a seq with an even number of elements. This seq gets grouped into pairs with (partition 2 message-validator-pairs)
. The first element of the pair should be an error message, and the second element of the pair should be a function (just like the pairs are arranged in order-details-validations
). The error-messages-for
function works by filtering out all error message and validation pairs where the validation function returns true
when applied to to-validate
. It then uses map first
to get the first element of each pair, the error message. Here it is in action:
(error-messages-for "" ["Please enter a name" not-empty])
; => ("Please enter a name")
However, this wouldn’t work, because success-code
and failure-code
would get evaluated each time. A macro would work because macros let you control evaluation. Here’s how you’d use the macro:
(if-valid order-details order-details-validation errors
+ (if-valid order-details order-details-validations errors
(render :success)
(render :failure errors))
@@ -604,7 +604,7 @@ Summary
Exercises
- Write the macro
when-valid
so that it behaves similarly to when
. Here is an example of calling it:
- (when-valid order-details order-details-validation
+ (when-valid order-details order-details-validations
(println "It's a success!")
(render :success))