2014-10-27 04:40:02 +01:00
title: Model Validation and Constraints
summary: Validate your data at the model level
# Validation and Constraints
Traditionally, validation in SilverStripe has been mostly handled on the controller through [form validation ](../forms ).
While this is a useful approach, it can lead to data inconsistencies if the record is modified outside of the
controller and form context.
Most validation constraints are actually data constraints which belong on the model. SilverStripe 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-08-03 05:57:29 +02:00
class MyObject extends DataObject
{
2014-10-27 04:40:02 +01:00
2017-08-03 05:35:09 +02:00
private static $db = [
2014-10-27 04:40:02 +01:00
'Country' => 'Varchar',
'Postcode' => 'Varchar'
2017-08-03 05:35:09 +02:00
];
2014-10-27 04:40:02 +01:00
2017-08-03 06:25:49 +02:00
public function validate()
{
2014-10-27 04:40:02 +01:00
$result = parent::validate();
if($this->Country == 'DE' & & $this->Postcode & & strlen($this->Postcode) != 5) {
$result->error('Need five digits for German postcodes');
}
return $result;
}
}
2017-08-03 05:35:09 +02:00
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 );