Validations

Version 6 (Kien La, 2010-06-19 06:09 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 1
On the contrary, 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 3 Kien La
h4(#available-validations). Available validations
116 1

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

                
119 3 Kien La
* "validates_presence_of":/projects/main/wiki/Validations#validates_presence_of
120 3 Kien La
* "validates_size_of":/projects/main/wiki/Validations#validates_size_of
121 6 Kien La
* "validates_length_of":/projects/main/wiki/Validations#validates_size_of
122 3 Kien La
* "validates_(in|ex)clusion_of":/projects/main/wiki/Validations#validates_in_ex_clusion_of
123 3 Kien La
* "validates_format_of":/projects/main/wiki/Validations#validates_format_of
124 3 Kien La
* "validates_numericality_of":/projects/main/wiki/Validations#validates_numericality_of
125 3 Kien La
* "validates_uniqueness_of":/projects/main/wiki/Validations#validates_uniqueness_of
126 3 Kien La
* "validates_presence_of":/projects/main/wiki/Validations#validates_presence_of
127 1

                
128 5 Kien La
h4(#validates_presence_of). validates_presence_of
129 4 Kien La

                
130 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:
131 1

                
132 1
* message: default: *can't be blank*
133 1

                
134 1
<pre class="code"><code class="php">
135 1
class Book extends ActiveRecord\Model
136 1
{
137 1
  static $validates_presence_of = array(
138 1
    array('title'),
139 1
    array('cover_blurb', 'message' => 'must be present and witty')
140 1
  );
141 1
}
142 1
 
143 1
$book = new Book(array('title' => ''));
144 1
$book->save();
145 1
 
146 1
echo $book->errors->on('cover_blurb'); # => must be present and witty
147 1
echo $book->errors->on('title'); # => can't be blank
148 1
</code></pre>
149 1

                
150 3 Kien La
h4(#validates_size_of). validates_size_of / validates_length_of
151 1

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

                
154 3 Kien La
*is*: attribute should be *exactly* n characters long
155 3 Kien La
*in/within*: attribute should be within an range array(1,5)
156 3 Kien La
*maximum/minimum*: attribute should not be above/below respectively
157 3 Kien La

                
158 1
Each of the options has a particular message and can be changed.
159 1

                
160 3 Kien La
* *is*: uses key 'wrong_length'
161 3 Kien La
* *in/within*: uses keys 'too_long' & 'too_short'
162 3 Kien La
* *maximum/minimum*: uses keys 'too_long' & 'too_short'
163 1

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

                
194 3 Kien La
h4(#validates_in_ex_clusion_of). validates_(in|ex)clusion_of
195 1

                
196 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:
197 1

                
198 3 Kien La
* *in/within*: attribute should/shouldn't be a value within an array
199 3 Kien La
* *message*: custom error message
200 1

                
201 1
<pre class="code"><code class="php">
202 1
class Car extends ActiveRecord\Model
203 1
{
204 1
  static $validates_inclusion_of = array(
205 1
    array('fuel_type', 'in' => array('hyrdogen', 'petroleum', 'bio-diesel', 'electric')),
206 1
  );
207 1
}
208 1
 
209 1
# this will pass since it's in the above list
210 1
$car = new Car(array('fuel_type' => 'electric'));
211 1
$ret = $car->save();
212 1
echo $ret # => true
213 1

                
214 1
class User extends ActiveRecord\Model
215 1
{
216 1
  static $validates_exclusion_of = array(
217 1
    array('password', 'in' => array('god', 'sex', 'password', 'love', 'secret'),
218 1
      'message' => 'should not be one of the four most used passwords')
219 1
  );
220 1
}
221 1
 
222 1
$user = new User;
223 1
$user->password = 'god';
224 1
$user->save();
225 1
echo $user->errors->on('password'); # => should not be one of the four most used passwords
226 1
</code></pre>
227 1

                
228 3 Kien La
h4(#validates_format_of). validates_format_of
229 1

                
230 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:
231 1

                
232 3 Kien La
* *with*: regular expression
233 3 Kien La
* *message*: custom error message
234 1

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

                
255 3 Kien La
h4(#validates_numericality_of). validates_numericality_of
256 1

                
257 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:
258 1

                
259 3 Kien La
* *only_integer*: value must be an integer (e.g. not a float), message: "is not a number"
260 3 Kien La
* *even, message*: "must be even"
261 3 Kien La
* *odd, message*: "must be odd"
262 3 Kien La
* *greater_than*: >, message: "must be greater than %d"
263 3 Kien La
* *greater_than_or_equal_to*: >=, message: "must be greater than or equal to %d"
264 3 Kien La
* *equal_to*: ==, message: "must be equal to %d"
265 3 Kien La
* *less_than*: <, message: "must be less than %d"
266 3 Kien La
* *less_than_or_equal_to*: <=, message: "must be less than or equal to %d"
267 1

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

                
292 3 Kien La
h4(#validates_uniqueness_of). validates_uniqueness_of
293 1

                
294 1
Tests whether or not a given attribute already exists in the table or not.
295 1

                
296 3 Kien La
* *message*: custom error message
297 1

                
298 1
<pre class="code"><code class="php">
299 1
class User extends ActiveRecord\Model
300 1
{
301 1
  static $validates_uniqueness_of = array(
302 1
    array('name'),
303 1
    array(array('blah','bleh'), 'message' => 'blah and bleh!')
304 1
  );
305 1
}
306 1
 
307 1
User::create(array('name' => 'Tito'));
308 1
$user = User::create(array('name' => 'Tito'));
309 1
$user->is_valid(); # => false
310 1
</code></pre>