2019-11-18 05:58:33 +01:00
---
2014-10-27 04:40:02 +01:00
title: Model Validation and Constraints
summary: Validate your data at the model level
2019-11-18 05:58:33 +01:00
icon: check-square
---
2014-10-27 04:40:02 +01:00
# Validation and Constraints
2021-06-30 11:48:52 +02:00
Traditionally, validation in Silverstripe CMS has been mostly handled on the controller through [form validation ](../forms ).
2014-10-27 04:40:02 +01:00
While this is a useful approach, it can lead to data inconsistencies if the record is modified outside of the
controller and form context.
2021-06-30 11:48:52 +02:00
Most validation constraints are actually data constraints which belong on the model. Silverstripe CMS provides the
2017-07-03 03:22:12 +02:00
[DataObject::validate() ](api:SilverStripe\ORM\DataObject::validate( )) method for this purpose.
2014-10-27 04:40:02 +01:00
By default, there is no validation - objects are always valid! However, you can overload this method in your DataObject
2017-07-03 03:22:12 +02:00
sub-classes to specify custom validation, or use the `validate` hook through a [DataExtension ](api:SilverStripe\ORM\DataExtension ).
2014-10-27 04:40:02 +01:00
2017-07-03 03:22:12 +02:00
Invalid objects won't be able to be written - a [ValidationException ](api:SilverStripe\ORM\ValidationException ) will be thrown and no write will occur.
2014-10-27 04:40:02 +01:00
It is expected that you call `validate()` in your own application to test that an object is valid before attempting a
write, and respond appropriately if it isn't.
2017-07-03 03:22:12 +02:00
The return value of `validate()` is a [ValidationResult ](api:SilverStripe\ORM\ValidationResult ) object.
2014-10-27 04:40:02 +01:00
2017-08-03 02:51:32 +02:00
```php
2017-10-27 04:38:27 +02:00
use SilverStripe\ORM\DataObject;
2017-08-05 00:45:24 +02:00
2017-10-27 04:38:27 +02:00
class MyObject extends DataObject
{
2014-10-27 04:40:02 +01:00
2017-10-27 04:38:27 +02:00
private static $db = [
'Country' => 'Varchar',
'Postcode' => 'Varchar'
];
2014-10-27 04:40:02 +01:00
2017-10-27 04:38:27 +02:00
public function validate()
{
$result = parent::validate();
2014-10-27 04:40:02 +01:00
2017-10-27 04:38:27 +02:00
if($this->Country == 'DE' & & $this->Postcode & & strlen($this->Postcode) != 5) {
2018-02-13 23:48:07 +01:00
$result->addError('Need five digits for German postcodes');
2017-08-07 05:11:17 +02:00
}
2017-08-03 05:35:09 +02:00
2017-10-27 04:38:27 +02:00
return $result;
}
}
2017-08-03 02:51:32 +02:00
```
2014-10-27 04:40:02 +01:00
## API Documentation
2017-07-03 03:22:12 +02:00
* [DataObject ](api:SilverStripe\ORM\DataObject )
* [ValidationResult ](api:SilverStripe\ORM\ValidationResult );