mirror of
https://github.com/silverstripe/silverstripe-framework
synced 2024-09-16 14:36:26 +02:00
fdbd899766
- Remaining Developer Guides and Upgrading - SilverStripe in a namespace or api has not been change - To keep PRs easier no formatting was changed Update merge conflics with two files Update Silverstripe Ltd, Silverstripe Cloud and Silverstripe CMS Silverstripe CMS Ltd > Silverstripe Ltd Silverstripe CMS Platform > Silverstripe Cloud Silverstripe CMS Framework > Silverstripe CMS Resolve merge conflict Remove Framework from Silverstripe CMS Framework - 3 files Change SilverStripe CMS to Silverstripe CMS
55 lines
1.9 KiB
Markdown
55 lines
1.9 KiB
Markdown
---
|
|
title: Model Validation and Constraints
|
|
summary: Validate your data at the model level
|
|
icon: check-square
|
|
---
|
|
|
|
# Validation and Constraints
|
|
|
|
Traditionally, validation in Silverstripe CMS 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 CMS provides the
|
|
[DataObject::validate()](api:SilverStripe\ORM\DataObject::validate()) method for this purpose.
|
|
|
|
By default, there is no validation - objects are always valid! However, you can overload this method in your DataObject
|
|
sub-classes to specify custom validation, or use the `validate` hook through a [DataExtension](api:SilverStripe\ORM\DataExtension).
|
|
|
|
Invalid objects won't be able to be written - a [ValidationException](api:SilverStripe\ORM\ValidationException) will be thrown and no write will occur.
|
|
|
|
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.
|
|
|
|
The return value of `validate()` is a [ValidationResult](api:SilverStripe\ORM\ValidationResult) object.
|
|
|
|
```php
|
|
use SilverStripe\ORM\DataObject;
|
|
|
|
class MyObject extends DataObject
|
|
{
|
|
|
|
private static $db = [
|
|
'Country' => 'Varchar',
|
|
'Postcode' => 'Varchar'
|
|
];
|
|
|
|
public function validate()
|
|
{
|
|
$result = parent::validate();
|
|
|
|
if($this->Country == 'DE' && $this->Postcode && strlen($this->Postcode) != 5) {
|
|
$result->addError('Need five digits for German postcodes');
|
|
}
|
|
|
|
return $result;
|
|
}
|
|
}
|
|
```
|
|
|
|
## API Documentation
|
|
|
|
* [DataObject](api:SilverStripe\ORM\DataObject)
|
|
* [ValidationResult](api:SilverStripe\ORM\ValidationResult);
|