silverstripe-framework/docs/en/02_Developer_Guides/00_Model/09_Validation.md
Aaron Carlino 6888901468
NEW: Update docs to be compliant with Gatsby site (#9314)
* First cut

* Temporarily disable composer.json for netlify build

* POC

* New recursive directory query, various refinements

* Fix flexbox

* new styled components plugin

* Apply frontmatter delimiters

* Mobile styles, animation

* Search

* Redesign, clean up

* Nuke the cache, try again

* fix file casing

* Remove production env file

* ID headers

* Move app to new repo

* Add frontmatter universally

* Hide children changelogs

* Add how to title

* New callout tags

* Revert inline code block change

* Replace note callouts

* Fix icons

* Repalce images

* Fix icon

* Fix image links

* Use proper SQL icon
2019-11-18 17:58:33 +13:00

1.8 KiB

title summary icon
Model Validation and Constraints Validate your data at the model level check-square

Validation and Constraints

Traditionally, validation in SilverStripe has been mostly handled on the controller through form validation.

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 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.

Invalid objects won't be able to be written - a 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 object.

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