10.04.2018 Views

Doctrine_manual-1-2-en

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 13: Data Validation 220<br />

$user->username = 'jwage';<br />

$user->favorite_color = 'red';<br />

if ( ! $user->isValid()) {<br />

echo 'User is invalid because "red" is not a valid hex color';<br />

}<br />

Range<br />

The range validator checks if value is within giv<strong>en</strong> range of numbers.<br />

Listing<br />

13-32<br />

// models/User.php<br />

class User ext<strong>en</strong>ds BaseUser<br />

{<br />

// ...<br />

public function setTableDefinition()<br />

{<br />

par<strong>en</strong>t::setTableDefinition();<br />

// ...<br />

}<br />

}<br />

$this->hasColumn('age', 'integer', 3, array(<br />

'range' => array(10, 100)<br />

)<br />

);<br />

Listing<br />

13-33<br />

Here is the same example in YAML format. You can read more about YAML in the YAML<br />

Schema Files (page 195) chapter:<br />

---<br />

# schema.yml<br />

# ...<br />

User:<br />

columns:<br />

# ...<br />

age:<br />

type: integer(3)<br />

range: [10, 100]<br />

# ...<br />

Now if you try and save a User with an age that is less than 10 or greater than 100, the<br />

validation will fail.<br />

Listing<br />

13-34<br />

// test.php<br />

// ...<br />

$user = new User();<br />

$user->username = 'jwage';<br />

$user->age = '3';<br />

if ( ! $user->isValid()) {<br />

----------------- Brought to you by

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!