Validations

Version 10 (Kien La, 2010-07-25 05:05 PM)

1 1
h2. Validations
2 1

                
3 2 Kien La
*(#topic-list) "Is my model valid or not?":/projects/main/wiki/Validations#is-my-model-valid-or-not
4 2 Kien La
* "Commonalities":/projects/main/wiki/Validations#commonalities
5 2 Kien La
* "Available validations":/projects/main/wiki/Validations#available-validations
6 2 Kien La
* "validates_presence_of":/projects/main/wiki/Validations#validates_presence_of
7 2 Kien La
* "validates_size_of / validates_length_of":/projects/main/wiki/Validations#validates_size_of
8 2 Kien La
* "validates_(in|ex)clusion_of":/projects/main/wiki/Validations#validates_in_ex_clusion_of
9 2 Kien La
* "validates_format_of":/projects/main/wiki/Validations#validates_format_of
10 2 Kien La
* "validates_numericality_of":/projects/main/wiki/Validations#validates_numericality_of
11 2 Kien La
* "validates_uniqueness_of":/projects/main/wiki/Validations#validates_uniqueness_of
12 2 Kien La

                
13 9 Ennio Wolsink
Validations offer a simple and powerful pattern to ensure the integrity of your data. By declaring validations on your models, you can be certain that only valid data will be saved to your database. No longer will you need to recall where you put that function which verifies the legitimacy of an e-mail and whether or not it will stop the record fom being saved. With validations, if your data is invalid, ActiveRecord will take care of marking the record as invalid instead of writing it to the database.
14 1

                
15 1
Validations will run for the following methods normally:
16 1

                
17 1
<pre class="code"><code class="php">
18 1
$book->save();
19 1
Book::create();
20 1
$book->update_attributes(array('title' => 'new title'));
21 1
</code></pre>
22 1
 
23 1
The following will skip validations and save the record:
24 1

                
25 1
<pre class="code"><code class="php">
26 1
$book->update_attribute();
27 1
$book->save(false); # anytime you pass false to save it will skip validations
28 1
</code></pre>
29 1
 
30 2 Kien La
h4(#is-my-model-valid-or-not). Is my model valid or not?
31 1

                
32 2 Kien La
You can determine whether or not your model is valid and can be saved to the database by issuing one of these methods: "Model::is_valid":/docs/ActiveRecord/Model#methodis_valid or "Model::is_invalid":/docs/ActiveRecord/Model#methodis_invalid. Both of these methods will run the validations for your model when invoked.
33 1

                
34 1
<pre class="code"><code class="php">
35 1
class Book extends ActiveRecord\Model
36 1
{
37 1
  static $validates_presence_of = array(
38 1
    array('title')
39 1
  );
40 1
}
41 1

                
42 1
# our book won't pass validates_presence_of
43 1
$book = new Book(array('title' => ''));
44 1
echo $book->is_valid(); # false
45 1
echo $book->is_invalid(); # true
46 1
</code></pre>
47 1
 
48 2 Kien La
If validation(s) fails for your model, then you can access the error message(s) like so. Let's assume that our validation was "validates_presence_of":/projects/main/wiki/Validations#validates_presence_of.
49 1

                
50 1
<pre class="code"><code class="php">
51 1
class Book extends ActiveRecord\Model
52 1
{
53 1
  static $validates_presence_of = array(
54 1
    array('title')
55 1
  );
56 1
}
57 1
 
58 1
$book = new Book(array('title' => ''));
59 1
$book->save();
60 1
$book->errors->is_invalid('title'); # => true
61 1

                
62 1
# if the attribute fails more than 1 validation,
63 1
# you would get an array of errors below
64 1

                
65 1
echo $book->errors->on('title'); # => can't be blank
66 1
</code></pre>
67 1
 
68 2 Kien La
Now let's assume our model failed two validations: "validates_presence_of":/projects/main/wiki/Validations#validates_presence_of and "validates_size_of":/projects/main/wiki/Validations#validates_size_of.
69 1

                
70 1
<pre class="code"><code class="php">
71 1
class Book extends ActiveRecord\Model
72 1
{
73 1
  static $validates_presence_of = array(
74 1
    array('title')
75 1
  );
76 1
 
77 1
  static $validates_size_of = array(
78 1
    array('title', 'within' => array(1,20))
79 1
  );
80 1
}
81 1
 
82 1
$book = new Book(array('title' => ''));
83 1
$book->save();
84 1
$book->errors->is_invalid('title'); # true
85 1

                
86 1
print_r($book->errors->on('title'));
87 1
 
88 1
# which would give us:
89 1

                
90 1
# Array
91 1
# (
92 1
#   [0] => can't be blank
93 1
#   [1] => is too short (minimum is 1 characters)
94 1
# )
95 1
</code></pre>
96 1

                
97 3 Kien La
h4(#commonalities). Commonalities
98 1

                
99 1
Validations are defined with a common set of options and some of them have specific options. As you've seen above, creating a validation is as simple as declaring a static validation variable in your model class as a multi-dimensional array (to validate multiple attributes). Each validation will require you to put the attribute name in the 0 index of the array. You can configure the error message by creating a message key with the message string as the value. You can also add an option which will only run the validation on either creation or update. By default, your validation will run everytime Model#save() is called.
100 1

                
101 1
<pre class="code"><code class="php">
102 1
class Book extends ActiveRecord\Model
103 1
{
104 1
  # 0 index is title, the attribute to test against
105 1
  # message is our custom error msg
106 1
  # only run this validation on creation - not when updating
107 1
  static $validates_presence_of = array(
108 1
    array('title', 'message' => 'cannot be blank on a book!', 'on' => 'create')
109 1
  );
110 1
}
111 1
</code></pre>
112 1

                
113 1
In some validations you may use: in, is within. In/within designate a range whereby you use an array with the first and second elements representing the beginning and end of the range respectively. Is represents equality.
114 1

                
115 10 Kien La
Common options available to all validators:
116 10 Kien La

                
117 10 Kien La
* *on:* run the validator during "save", "update" or "delete"
118 10 Kien La
* *allow_null:* allow null to satisfy the validation
119 10 Kien La
* *allow_blank:* allow a blank string to satisfy the validation
120 10 Kien La
* *message:* specify a custom error message
121 10 Kien La

                
122 3 Kien La
h4(#available-validations). Available validations
123 1

                
124 1
There are a number of pre-defined validation routines that you can declare on your model for specific attributes.
125 1

                
126 3 Kien La
* "validates_presence_of":/projects/main/wiki/Validations#validates_presence_of
127 3 Kien La
* "validates_size_of":/projects/main/wiki/Validations#validates_size_of
128 6 Kien La
* "validates_length_of":/projects/main/wiki/Validations#validates_size_of
129 3 Kien La
* "validates_(in|ex)clusion_of":/projects/main/wiki/Validations#validates_in_ex_clusion_of
130 3 Kien La
* "validates_format_of":/projects/main/wiki/Validations#validates_format_of
131 3 Kien La
* "validates_numericality_of":/projects/main/wiki/Validations#validates_numericality_of
132 3 Kien La
* "validates_uniqueness_of":/projects/main/wiki/Validations#validates_uniqueness_of
133 3 Kien La
* "validates_presence_of":/projects/main/wiki/Validations#validates_presence_of
134 1

                
135 5 Kien La
h4(#validates_presence_of). validates_presence_of
136 4 Kien La

                
137 1
This is probably the simplest of all the validations. It will make sure that the value of the attribute is not null or a blank string. Available options:
138 1

                
139 1
* message: default: *can't be blank*
140 1

                
141 1
<pre class="code"><code class="php">
142 1
class Book extends ActiveRecord\Model
143 1
{
144 1
  static $validates_presence_of = array(
145 1
    array('title'),
146 1
    array('cover_blurb', 'message' => 'must be present and witty')
147 1
  );
148 1
}
149 1
 
150 1
$book = new Book(array('title' => ''));
151 1
$book->save();
152 1
 
153 1
echo $book->errors->on('cover_blurb'); # => must be present and witty
154 1
echo $book->errors->on('title'); # => can't be blank
155 1
</code></pre>
156 1

                
157 3 Kien La
h4(#validates_size_of). validates_size_of / validates_length_of
158 1

                
159 1
These two validations are one and the same. The purpose is to validate the length in characters of a given attribute. Available options:
160 1

                
161 3 Kien La
*is*: attribute should be *exactly* n characters long
162 8 Szymon W
*in/within*: attribute should be within an range array(n, m)
163 3 Kien La
*maximum/minimum*: attribute should not be above/below respectively
164 3 Kien La

                
165 1
Each of the options has a particular message and can be changed.
166 1

                
167 3 Kien La
* *is*: uses key 'wrong_length'
168 3 Kien La
* *in/within*: uses keys 'too_long' & 'too_short'
169 3 Kien La
* *maximum/minimum*: uses keys 'too_long' & 'too_short'
170 1

                
171 1
<pre class="code"><code class="php">
172 1
class Book extends ActiveRecord\Model
173 1
{
174 1
  static $validates_size_of = array(
175 1
    array('title', 'within' => array(1,5), 'too_short' => 'too short!'),
176 1
    array('cover_blurb', 'is' => 20),
177 1
    array('description', 'maximum' => 10, 'too_long' => 'should be short and sweet')
178 1
  );
179 1
}
180 1
 
181 1
$book = new Book;
182 1
$book->title = 'War and Peace';
183 1
$book->cover_blurb = 'not 20 chars';
184 1
$book->description = 'this description is longer than 10 chars';
185 1
$ret = $book->save();
186 1
 
187 1
# validations failed so we get a false return
188 1
if ($ret == false)
189 1
{
190 1
  # too short!
191 1
  echo $book->errors->on('title');
192 1
 
193 1
  # is the wrong length (should be 20 chars)
194 1
  echo $book->errors->on('cover_blurb');
195 1
 
196 1
  # should be short and sweet
197 1
  echo $book->errors->on('description');
198 1
}
199 1
</code></pre>
200 1

                
201 3 Kien La
h4(#validates_in_ex_clusion_of). validates_(in|ex)clusion_of
202 1

                
203 3 Kien La
As you can see from the names, these two are similar. In fact, this is just a white/black list approach to your validations. Inclusion is a whitelist that will require a value to be within a given set. Exclusion is the opposite: a blacklist that requires a value to *not* be within a given set. Available options:
204 1

                
205 3 Kien La
* *in/within*: attribute should/shouldn't be a value within an array
206 3 Kien La
* *message*: custom error message
207 1

                
208 1
<pre class="code"><code class="php">
209 1
class Car extends ActiveRecord\Model
210 1
{
211 1
  static $validates_inclusion_of = array(
212 7 Kien La
    array('fuel_type', 'in' => array('petroleum', 'hydrogen', 'electric')),
213 1
  );
214 1
}
215 1
 
216 1
# this will pass since it's in the above list
217 1
$car = new Car(array('fuel_type' => 'electric'));
218 1
$ret = $car->save();
219 1
echo $ret # => true
220 1

                
221 1
class User extends ActiveRecord\Model
222 1
{
223 1
  static $validates_exclusion_of = array(
224 1
    array('password', 'in' => array('god', 'sex', 'password', 'love', 'secret'),
225 1
      'message' => 'should not be one of the four most used passwords')
226 1
  );
227 1
}
228 1
 
229 1
$user = new User;
230 1
$user->password = 'god';
231 1
$user->save();
232 7 Kien La

                
233 7 Kien La
# => should not be one of the four most used passwords
234 7 Kien La
echo $user->errors->on('password');
235 1
</code></pre>
236 1

                
237 3 Kien La
h4(#validates_format_of). validates_format_of
238 1

                
239 3 Kien La
This validation uses "preg_match":http://www.php.net/preg_match to verify the format of an attribute. You can create a regular expression to test against. Available options:
240 1

                
241 3 Kien La
* *with*: regular expression
242 3 Kien La
* *message*: custom error message
243 1

                
244 1
<pre class="code"><code class="php">
245 1
class User extends ActiveRecord\Model
246 1
{
247 1
  static $validates_format_of = array(
248 1
    array('email', 'with' =>
249 1
      '/^[^0-9][A-z0-9_]+([.][A-z0-9_]+)*[@][A-z0-9_]+([.][A-z0-9_]+)*[.][A-z]{2,4}$/')
250 1
    array('password', 'with' =>
251 1
      '/^.*(?=.{8,})(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).*$/', 'message' => 'is too weak')
252 1
  );
253 1
}
254 1
 
255 1
$user = new User;
256 1
$user->email = 'not_a_real_email.com';
257 1
$user->password = 'notstrong';
258 1
$user->save();
259 1
 
260 1
echo $user->errors->on('email'); # => is invalid
261 1
echo $user->errors->on('password'); # => is too weak
262 1
</code></pre>
263 1

                
264 3 Kien La
h4(#validates_numericality_of). validates_numericality_of
265 1

                
266 1
As the name suggests, this gem tests whether or not a given attribute is a number, and whether or not it is of a certain value. Available options:
267 1

                
268 3 Kien La
* *only_integer*: value must be an integer (e.g. not a float), message: "is not a number"
269 3 Kien La
* *even, message*: "must be even"
270 3 Kien La
* *odd, message*: "must be odd"
271 3 Kien La
* *greater_than*: >, message: "must be greater than %d"
272 3 Kien La
* *greater_than_or_equal_to*: >=, message: "must be greater than or equal to %d"
273 3 Kien La
* *equal_to*: ==, message: "must be equal to %d"
274 3 Kien La
* *less_than*: <, message: "must be less than %d"
275 3 Kien La
* *less_than_or_equal_to*: <=, message: "must be less than or equal to %d"
276 1

                
277 1
<pre class="code"><code class="php">
278 1
class Order extends ActiveRecord\Model
279 1
{
280 1
  static $validates_numericality_of = array(
281 1
    array('price', 'greater_than' => 0.01),
282 1
    array('quantity', 'only_integer' => true),
283 1
    array('shipping', 'greater_than_or_equal_to' => 0),
284 1
    array('discount', 'less_than_or_equal_to' => 5, 'greater_than_or_equal_to' => 0)
285 1
  );
286 1
}
287 1
 
288 1
$order = new Order;
289 1
$order->price = 0;
290 1
$order->quantity = 1.25;
291 1
$order->shipping = 5;
292 1
$order->discount = 2;
293 1
$order->save();
294 1
 
295 1
echo $order->errors->on('price'); # => must be greater than 0.01
296 1
echo $order->errors->on('quantity'); # => is not a number
297 1
echo $order->errors->on('shipping'); # => null
298 1
echo $order->errors->on('discount'); # => null
299 1
</code></pre>
300 1

                
301 3 Kien La
h4(#validates_uniqueness_of). validates_uniqueness_of
302 1

                
303 1
Tests whether or not a given attribute already exists in the table or not.
304 1

                
305 3 Kien La
* *message*: custom error message
306 1

                
307 1
<pre class="code"><code class="php">
308 1
class User extends ActiveRecord\Model
309 1
{
310 1
  static $validates_uniqueness_of = array(
311 1
    array('name'),
312 1
    array(array('blah','bleh'), 'message' => 'blah and bleh!')
313 1
  );
314 1
}
315 1
 
316 1
User::create(array('name' => 'Tito'));
317 1
$user = User::create(array('name' => 'Tito'));
318 1
$user->is_valid(); # => false
319 1
</code></pre>