A-la-carte
You can also define constraints a-la-carte. Meaning you can create them on the fly or store them as JSON or somewhere in a service. As long as it is a struct of constraints, that's all the validation methods accept via the constraints argument.
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.
1
// sample REST API create user
2
function create( event, rc, prc ){
3
var validationResult = validate(
4
target = rc,
5
constraints = {
6
username : { required : true },
7
email : { required : true, type : "email" },
8
password : { required : true }
9
}
10
)
11
if ( !validationResult.hasErrors() ) {
12
UserService.createUser( rc.username, rc.email, rc.password );
13
prc.response.setData( UserService.readUser( username = rc.username ) );
14
} else {
15
prc.response
16
.setError( true )
17
.addMessage( validationResult.getAllErrors() )
18
.setStatusCode( STATUS.BAD_REQUEST )
19
.setStatusText( "Validation error" );
20
}
21
}
Copied!
Last modified 1yr ago
Copy link