Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Here are the module settings you can place in your ColdBox.cfc
by using the validation
settings structure:
Important: The module will register several objects into WireBox using the @cbvalidation
namespace. The validation manager is registered as ValidationManager@cbvalidation
Key
Type
Required
Default
Description
manager
instantiation path or WireBox ID
false
cbValidation.models.ValidationManager
You can override the module manager with your own implementation. Just use an instantiation path or a valid WireBox object id.
sharedConstraints
struct
false
{}
This structure will hold all of your shared constraints for forms or/and objects.
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
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:
Just drop into your modules folder or use CommandBox to install
box install cbvalidation
The module will register several objects into WireBox using the @cbvalidation
namespace. The validation manager is registered as ValidationManager@cbvalidation
. It will also register several helper methods that can be used throughout the ColdBox application.
The module will also register two methods in your handlers/interceptors/layouts/views
validate()
validateOrFail()
getValidationManager()
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 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.
We also setup lots of global {Key}
replacements for your messages and also several that the core constraint validators offer as well. This is great for adding these customizations on your custom messages and also your i18n messages (Keep Reading):
{rejectedValue}
- The rejected value
{field or property}
- The property or field that was validated
{validationType}
- The name of the constraint validator
{validationData}
- The value of the constraint definition, e.g size=5..10, then this value is 5..10
{DiscreteValidator}
- operation, operationValue
{InListValidator}
- inList
{MaxValidator}
- max
{MinValidator}
- min
{RangeValidator}
- range, min, max
{RegexValidator}
- regex
{SameAsValidator}
, {SameAsNoCaseValidator}
- sameas
{SizeValidator}
- size, min, max
{TypeValidator}
- type
This module is a server side rules validation engine that can provide you with a unified approach to object, struct and form validation. You can construct validation constraint rules and then tell the engine to validate them accordingly.
Lucee 5+
ColdFusion 2016+
ColdBox validation is based on a way to declaratively specify validation rules for properties or fields in an object or form. The constraints can exist inside of the target object or you can define object and form constraints in your ColdBox configuration file so you can reuse validation constraints or as we call them: shared constraints.
You can then use 2 simple validation methods and report on the results: validate(), validateOrFail()
The ColdBox ORM Module is a professional open source software backed by Ortus Solutions, Corp offering services like:
Custom Development
Professional Support & Mentoring
Training
Server Tuning
Security Hardening
Code Reviews
Because of His grace, this project exists. If you don't like this, then don't read it, it's not for you.
"Therefore being justified by faith, we have peace with God through our Lord Jesus Christ: By whom also we have access by faith into this grace wherein we stand, and rejoice in hope of the glory of God." Romans 5:5
By default if a constraint fails an error message will be set in the result objects for you in English. If you would like to have your own custom messages for specific constraints you can do so by following the constraint message convention:
Just add the name of the constraint you like and append to it the work Message and you are ready to roll:
The unique
constraint is part of the module. So make sure that the cborm
module is installed first.
See the for a uniqueness validator which is not dependent of ORM
The constraints is mapped into WireBox as UniqueValidator@cborm
so you can use in your constraints like so:
If you will be using the unique constraint, then the name of the property has to be EXACTLY the same case as the constraint name. To do this, use single or double quotes to declare the constraint name. Please see example below.
In cbValidation 1.5 we introduced the validateOrFail()
function. This function works in similar manner to the validate()
method, but instead of giving you the results object, it throws an exception.
So your validation fails, where are the results? In the exception structure under the extendedInfo
key. We store the validation results as JSON in the extended info and then you can use them for display purposes:
Below are all the currently supported constraints. If you need more you can create your own .
With the validator
constraint you can specify your own custom validator, but if you need your own parameters for your validator this is a bit limited. You can also specify YourOwnValidator
as constraint label where YourOwnValidator
is a wirebox id string. In this case you can specify your own parameters.
WARNING: You can't do a normal wirebox mapping for YourOwnValidator
in your main application. A validator needs an IValidator
interface from the cbvalidation
module. When wirebox inspects the binder, the cbvalidation
module is not loaded yet, so it will error. This can be solved by defining your custom validators in an own module (depending on cbvalidation
) or by mapping your validator in the afterConfigurationLoad()
method of your binder, e.g in config/wirebox.cfc
Most likely you will be validating your objects at the controller layer in your ColdBox event handlers. All event handlers,layouts, views and interceptors have some new methods thanks to our module mixins.
You pass in your target object or structure, an optional list of fields or properties to validate only (by default it does all of them), an an optional constraints argument which can be the shared name or an actual constraints structure a-la-carte. If no constraints are passed, then we will look for the constraints in the target object as a public property called constraints
. The validate()
method returns a cbvalidation.models.results.IValidationResult
type object, which you can then use for evaluating the validation.
The return of validate model is our results interface which has cool methods like:
Some of these methods return error objects which adhere to our Error Interface: cbvalidation.models.result.IValidationError
, which can quickly tell you what field had the exception, what was the rejected value and the validation message:
See for details.
Constraint | Type | Default |
| boolean | false | Whether the property must have a non-null value |
| string | string | Validates that the value is of a certain format type. Our included types are: ssn,email,url,alpha,boolean,date,usdate,eurodate,numeric,GUID,UUID,integer,string,telephone,zipcode,ipaddress,creditcard,binary,component,query,struct,json,xml |
| numeric or range | --- | The size or length of the value which can be a struct, string, array, or query. The value can be a single numeric value or our cool ranges. Ex: size=4, size=6..8, size=-5..0 |
| range | --- | Range is a range of values the property value should exist in. Ex: range=1..10, range=6..8 |
| regular expression | --- | The regular expression to try and match the value with for validation. This is a no case regex check. |
| propertyName | --- | Makes sure the value of the constraint is the same as the value of another property in the object. This is a case sensitive check. |
| propertyName | --- | Makes sure the value of the constraint is the same as the value of another property in the object with no case sensitivity. |
| string list | --- | A list of values that the property value must exist in |
| string | --- | Do discrete math in the property value. The valid values are: eq,neq,lt,lte,gt,gte. Example: discrete="eq:4" or discrete="lte:10" |
| UDF or closure | --- | I can do my own custom validation by doing an inline closure (CF 10 or Railo only) or a pointer to a custom defined function. The function must return boolean and accepts two parameters: value and target. |
| method name | --- | The name of a method to call in the target object for validation. The function must return boolean and accepts two parameters: value and target. |
| numeric | --- | The value must be greater than or equal to this minimum value |
| numeric | --- | The value must be less than or equal to this maximum value |
| instantiation path or wirebox DSL | --- | You can also build your own validators instead of our internal ones. This value will be the instantiation path to the validator or a wirebox id string. Example: validator="mymodel.validators.MyValidator", validator="id:MyValidator" |
Incoming Target | Validation Fails | Result |
Object | false | Returns the same object |
Object | true | Throws |
Struct | false | Returns the structure with ONLY the fields that were validated from the constraints |
Struct | true | Throws |
The module will register several objects into WireBox using the @cbvalidation
namespace. The validation manager is registered as ValidationManager@cbvalidation
, which is the one you can inject and use anywhere you like.
We also have the ability to validate a target object or form with shared constraints from our configuration file. Just use the name of the key in the configuration form as the name of the constraints
argument.
This will validate the object and rc
using the sharedUser
constraints.
We also have the ability to validate a target object with custom a-la-carte constraints by passing the constraints inline as an struct of structs. This way you can store these constraint rules anywhere you like.
This will validate the object using the inline constraints that you built.
After validation you can use the same results object and use it to display the validation errors in your client side:
If you want more control you can use the hasErrors()
and iterate over the errors to display:
You can even use the results object in your views to get specific field errors, messagesbox, etc.
The following are some common methods from the validation result object for dealing with errors:
getResultMetadata()
getFieldErrors( [field] )
getAllErrors( [field] )
getAllErrorsAsJSON( [field] )
getAllErrorsAsStruct( [field] )
getErrorCount( [field] )
hasErrors( [field] )
getErrors()
The API Docs in the module (once installed) will give you the latest information about these methods and arguments.
If you are using i18n (Internationalization and Localization) in your ColdBox applications you can also localize your validation error messages from the ColdBox validators.
Info You do not need to install the cbi18n
module. This module is already a dependency of the cbvalidation
module.
You will do this by our lovely conventions for you resource bundle keys:
We also setup lots of global {Key}
replacements for your messages and also several that the core constraint validators offer as well:
{rejectedValue}
- The rejected value
{field}
or property - The property or field that was validated
{validationType}
- The name of the constraint validator
{validationData}
- The value of the constraint definition, e.g size=5..10, then this value is 5..10
{targetName}
- The name of the user, shared constraint or form
{DiscreteValidator}
- operation, operationValue
{InListValidator}
- inList
{MaxValidator}
- max
{MinValidator}
- min
{RangeValidator}
- range, min, max
{RegexValidator}
- regex
{SameAsValidator}
, {SameAsNoCaseValidator}
- SameAs
{SizeValidator}
- size, min, max
{TypeValidator}
- type
You can use multiple custom validators or pass in arbitrary data to custom validators by specifying the validator name as the key in the rules struct.
This example will look for a UniqueInDBValidator
in WireBox and pass in { table = "table_name", column = "column_name" }
to the validate
method.
Using these advanced techniques you can build reusable validators that accept the data they need in the validationData
struct. You can also include multiple custom validators just by specifying each of them as a key.
If you don't have any custom data to pass to a validator, just pass an empty struct ({}
)
WARNING: You can't do a normal wirebox mapping for YourOwnValidator
in your main application. A validator needs an IValidator
interface from the cbvalidation
module. When wirebox inspects the binder, the cbvalidation
module is not loaded yet, so it will error. This can be solved by defining your custom validators in an own module (depending on cbvalidation
) or by mapping your validator in the afterConfigurationLoad()
method of your binder, e.g in config/wirebox.cfc
You can build also your own validators by implementing our interface cbvalidaton.models.validators.IValidator
:
The arguments received are:
validationResults
: The validation result object
field
: The field or property in the object that is in validation
targetValue
: The value to test
Here is a sample validator:
WARNING: You can't do a normal wirebox mapping for YourOwnValidator
in your main application. A validator needs an IValidator
interface from the cbvalidation
module. When wirebox inspects the binder, the cbvalidation
module is not loaded yet, so it will error. This can be solved by defining your custom validators in an own module (depending on cbvalidation
) or by mapping your validator in the afterConfigurationLoad()
method of your binder, e.g in config/wirebox.cfc
If you would like to adapt your own validation engines to work with ANY ColdBox application you can do this by implementing the following interfaces:
Validation Manager : Implement the cbvalidation.models.IValidationManager
. Then use the class path in your configuration file so it uses your validation manager instead of ours.
Validation Results : Implement the cbvalidation.models.result.IValidationResult
, which makes it possible for any ColdBox application to use your validation results.
Validation Error : Implement the cbvalidation.models.result.IValidationError
, which makes it possible for any ColdBox application to use your validation error representations.
You can also tell the validation manager to ONLY validate on certain fields and not all the fields declared in the validation constraints.
This will only validate the login
and password
fields.