You can also define your constraints on the fly right where you are doing your validation.
In this sample we validate the public request context rc
. This sample validates all fields in the rc
. If you need more control you can specify the fields
parameter (default all) or the includeFields
and excludeFields
parameters in your validate()
call.
You can define constraints in several locations:
When validating using validate(), validateOrFail()
you have to specify a target, but specifying a constraint in your call is optional.
When you call the validation methods with NO constraints
passed explicitly, then the validation module will following this lookup procedure:
Lookup your constraints in myTarget.constraints
struct in your target object or struct.
If you specify your constraint parameter as a string, the validator will lookup a shared constraint in your configuration file.
If you specify your constraint parameter as a struct, this struct will directly server as your set of constraints, so you can specify your constraints on the fly, or specify an alternative set of constraints in your model, e.g User.constraints
vs User.signInConstraints
Within any domain object you can define a public variable called constraints
that is a assigned an implicit structure of validation rules for any fields or properties in your object.
We can then create the validation rules for the properties it will apply to it:
That easy! You can just declare these validation rules and ColdBox will validate your properties according to the rules. In this case you can see that a password must be between 6 and 10 characters long, and it cannot be blank.
By default all properties are of type string and not required
You can then use them implicitly
You can optionally register shared constraints in your ColdBox configuration file under the validation
directive. This means you register them with a unique name of your choice and its value is a collection of constraints for properties in your objects or forms.
Later on you will reference the key name in your handlers or wherever in order to validate the object or form. Here is an example:
As you can see, our constraints definition describes the set of rules for a property on ANY target object or form.
You can then use the keys for those constraints in the validation calls: