cbValidation
Search…
Validating Constraints

Validation Methods: validate(), validateOrFail()

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.
1
/**
2
* Validate an object or structure according to the constraints rules.
3
*
4
* @target An object or structure to validate
5
* @fields The fields to validate on the target. By default, it validates on all fields
6
* @constraints A structure of constraint rules or the name of the shared constraint rules to use for validation
7
* @locale The i18n locale to use for validation messages
8
* @excludeFields The fields to exclude from the validation
9
* @includeFields The fields to include in the validation
10
* @profiles If passed, a list of profile names to use for validation constraints
11
*
12
* @return cbvalidation.model.result.IValidationResult
13
*/
14
function validate()
15
16
/**
17
* Validate an object or structure according to the constraints rules and throw an exception if the validation fails.
18
* The validation errors will be contained in the `extendedInfo` of the exception in JSON format
19
*
20
* @target An object or structure to validate
21
* @fields The fields to validate on the target. By default, it validates on all fields
22
* @constraints A structure of constraint rules or the name of the shared constraint rules to use for validation
23
* @locale The i18n locale to use for validation messages
24
* @excludeFields The fields to exclude from the validation
25
* @includeFields The fields to include in the validation
26
* @profiles If passed, a list of profile names to use for validation constraints
27
*
28
* @return The validated object or the structure fields that where validated
29
* @throws ValidationException
30
*/
31
function validateOrFail()
32
33
/**
34
* Retrieve the application's configured Validation Manager
35
*/
36
function getValidationManager()
Copied!
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), and 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.
Please note that you can validate using a procedural approach or a functional approach by using our onError() and onSuccess() callback methods.
1
// Validation using the results object procedurally
2
function saveUser( event, rc, prc ){
3
// create and populate a user object from an incoming form
4
var user = populateModel( entityNew("User") );
5
// validate model and get validation results object
6
prc.validationResults = validate( user );
7
// check for errors
8
if( prc.validationResults.hasErrors() ){
9
messagebox.error( prc.validationResults.getAllErrors() );
10
relocate( "users/editor" );
11
}
12
else{
13
userService.save( user );
14
}
15
}
16
17
// Validation using the results object functionally
18
function saveUser( event, rc, prc ){
19
// create and populate a user object from an incoming form
20
var user = populateModel( entityNew("User") );
21
22
validate( user )
23
.onError( function( results ){
24
messagebox.error( results.getAllErrors() );
25
relocate( "users/editor" );
26
})
27
.onSuccess( function( results ){
28
userService.save( user );
29
});
30
31
}
32
33
// Validation using Active Entity and validate or fail
34
function save( event, rc, prc ){
35
userService
36
.getOrFail( rc.id )
37
.populate()
38
.validateOrFail()
39
.save();
40
}
Copied!

Validation Results

The return of the validate() method is our results object cbvalidation.models.result.ValidationResult which has several methods that you can use to interact with the validation results. Usually you woul use the onError() and onSuccess() callbacks to finalize the validation.
1
/**
2
* Add errors into the result object
3
* @error The validation error to add into the results object
4
* @error_generic IValidationError
5
*
6
* @return IValidationResult
7
*/
8
any function addError(required error);
9
10
/**
11
* Set the validation target object name
12
* @return IValidationResult
13
*/
14
any function setTargetName(required string name);
15
16
/**
17
* Get the name of the target object that got validated
18
*/
19
string function getTargetName();
20
21
/**
22
* Get the validation locale
23
*/
24
string function getValidationLocale();
25
26
/**
27
* has locale information
28
*/
29
boolean function hasLocale();
30
31
/**
32
* Set the validation locale
33
*
34
* @return IValidationResult
35
*/
36
any function setLocale(required string locale);
37
38
39
/**
40
* Determine if the results had error or not
41
* @fieldThe field to count on (optional)
42
*/
43
boolean function hasErrors(string field);
44
45
/**
46
* Clear All errors
47
* @return IValidationResult
48
*/
49
any function clearErrors();
50
51
52
/**
53
* Get how many errors you have
54
* @fieldThe field to count on (optional)
55
*/
56
numeric function getErrorCount(string field);
57
58
/**
59
* Get the Errors Array, which is an array of error messages (strings)
60
* @fieldThe field to use to filter the error messages on (optional)
61
*/
62
array function getAllErrors(string field);
63
64
/**
65
* Get an error object for a specific field that failed. Throws exception if the field does not exist
66
* @fieldThe field to return error objects on
67
*
68
* @return IValidationError[]
69
*/
70
array function getFieldErrors(required string field);
71
72
/**
73
* Get a collection of metadata about the validation results
74
*/
75
struct function getResultMetadata();
76
77
/**
78
* Set a collection of metadata into the results object
79
*
80
* @return IValidationResult
81
*/
82
any function setResultMetadata(required struct data);
83
84
/**
85
* Call back that will be executed if the validation results had errors in them.
86
* The consumer receives the results instance: `(results) => {}, function( results ){}`
87
*
88
* @consumer Block to be executed if the result of the validation had errors.
89
*
90
* @return Same instance
91
*/
92
function onError( required consumer )
93
94
/**
95
* Call back that will be executed if the validation results had NO errors in them.
96
* The consumer receives the results instance: `(results) => {}, function( results ){}`
97
*
98
* @consumer Block to be executed if the result of the validation had NO errors.
99
*
100
* @return Same instance
101
*/
102
function onSuccess( required consumer )
Copied!

Validation Error Object

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:
1
/**
2
* Copyright since 2020 by Ortus Solutions, Corp
3
* www.ortussolutions.com
4
* ---
5
* The ColdBox validation error interface, all inspired by awesome Hyrule Validation Framework by Dan Vega
6
*/
7
import cbvalidation.models.result.*;
8
interface {
9
10
/**
11
* Set the error message
12
* @messageThe error message
13
*/
14
IValidationError function setMessage( required string message );
15
16
/**
17
* Set the field
18
* @messageThe error message
19
*/
20
IValidationError function setField( required string field );
21
22
/**
23
* Set the rejected value
24
* @valueThe rejected value
25
*/
26
IValidationError function setRejectedValue( required any value );
27
28
/**
29
* Set the validator type name that rejected
30
* @validationTypeThe name of the rejected validator
31
*/
32
IValidationError function setValidationType( required any validationType );
33
34
/**
35
* Get the error validation type
36
*/
37
string function getValidationType();
38
39
/**
40
* Set the validator data
41
* @dataThe data of the validator
42
*/
43
IValidationError function setValidationData( required any data );
44
45
/**
46
* Get the error validation data
47
*/
48
string function getValidationData();
49
50
/**
51
* Get the error message
52
*/
53
string function getMessage();
54
55
/**
56
* Get the error field
57
*/
58
string function getField();
59
60
/**
61
* Get the rejected value
62
*/
63
any function getRejectedValue();
64
65
}
Copied!