-
Notifications
You must be signed in to change notification settings - Fork 5
2B. Validation
CBMongoDB includes validation functions to ensure schema enforcement at the application level. By providing a validate
, length
, required
or unique
attribute in your schema properties, you can leverage validation in your entities. Take, for example, our address schema properties from our example Person model:
property name="address" schema=true validate="struct";
/**Use either dot notation in the name or specify a 'parent' attribute as ways of creating nested documents**/
/**Dot Notation Examples**
property name="address.street" schema=true validate="string";
property name="address.city" schema=true validate="string";
property name="address.state" schema=true validate="string" length=2;
property name="address.postalcode" schema=true validate="zipcode";
property name="address.country" schema=true validate="string";
Validation types use the CFML native isValid()
type arguments. Using the schema above, a check of the entity with Person.isValid()
would perform the following checks:
-
address
is a struct -
street
,city
,state
, andcountry
are strings -
postalcode
is a valid US ZIP Code -
state
has a length equal to 2
If a record fails validation the results are available through the getValidationResults()
method which returns a struct containing an array of errors:
{
"success":false,
"errors":[
{
"message":"Invalid field value type for property phone.home",
"mapping":{
"required":"yes",
"name":"phone.home",
"schema":"true",
"type":"any",
"validate":"telephone"
},
"fieldName":"phone.home",
"type":"validation",
"fieldValue":"ABCDEFGHIJKLMNOP",
"description":"Property phone.home failed validation for type telephone. The type received was java.lang.String"
}
]
}
By default, validation is not required to save documents as, apart from specific BSON objects, MongoDB documents can handle any serializable or simple data type. You may, however, choose to enforce strict typing and validation by adding the following property to your models:
property name="ForceValidation" default=true;
If this property exists and is true, attempting to save a document which doesn't meet validation will throw an error, similar to the strict Java types enforced by Hibernate ORM.
-
isValid()
- Validates the entity. -
getValidationResults()
- Returns the struct containing the array of validation errors and additional mapping data. Will return null if validation has not yet been run -
getValidationErrors()
- Convenience method, which only returns the array of validation errors
Note: i18n support for validation errors is planned for a future release