Validations

Version 1 (Kien La, 2010-06-19 05:57 PM)

1 1
h2. Validations
2 1

                
3 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.
4 1

                
5 1
Validations will run for the following methods normally:
6 1

                
7 1
<pre class="code"><code class="php">
8 1
$book->save();
9 1
Book::create();
10 1
$book->update_attributes(array('title' => 'new title'));
11 1
</code></pre>
12 1
 
13 1
The following will skip validations and save the record:
14 1

                
15 1
<pre class="code"><code class="php">
16 1
$book->update_attribute();
17 1
$book->save(false); # anytime you pass false to save it will skip validations
18 1
</code></pre>
19 1
 
20 1
Is my model valid or not?
21 1

                
22 1
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 or Model::is_invalid. Both of these methods will run the validations for your model when invoked.
23 1

                
24 1
<pre class="code"><code class="php">
25 1
class Book extends ActiveRecord\Model
26 1
{
27 1
  static $validates_presence_of = array(
28 1
    array('title')
29 1
  );
30 1
}
31 1

                
32 1
# our book won't pass validates_presence_of
33 1
$book = new Book(array('title' => ''));
34 1
echo $book->is_valid(); # false
35 1
echo $book->is_invalid(); # true
36 1
</code></pre>
37 1
 
38 1
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.
39 1

                
40 1
<pre class="code"><code class="php">
41 1
class Book extends ActiveRecord\Model
42 1
{
43 1
  static $validates_presence_of = array(
44 1
    array('title')
45 1
  );
46 1
}
47 1
 
48 1
$book = new Book(array('title' => ''));
49 1
$book->save();
50 1
$book->errors->is_invalid('title'); # => true
51 1

                
52 1
# if the attribute fails more than 1 validation,
53 1
# you would get an array of errors below
54 1

                
55 1
echo $book->errors->on('title'); # => can't be blank
56 1
</code></pre>
57 1
 
58 1
Now let's assume our model failed two validations: validates_presence_of and validates_size_of.
59 1

                
60 1
<pre class="code"><code class="php">
61 1
class Book extends ActiveRecord\Model
62 1
{
63 1
  static $validates_presence_of = array(
64 1
    array('title')
65 1
  );
66 1
 
67 1
  static $validates_size_of = array(
68 1
    array('title', 'within' => array(1,20))
69 1
  );
70 1
}
71 1
 
72 1
$book = new Book(array('title' => ''));
73 1
$book->save();
74 1
$book->errors->is_invalid('title'); # true
75 1

                
76 1
print_r($book->errors->on('title'));
77 1
 
78 1
# which would give us:
79 1

                
80 1
# Array
81 1
# (
82 1
#   [0] => can't be blank
83 1
#   [1] => is too short (minimum is 1 characters)
84 1
# )
85 1
</code></pre>
86 1

                
87 1
Commonalities
88 1

                
89 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.
90 1

                
91 1
<pre class="code"><code class="php">
92 1
class Book extends ActiveRecord\Model
93 1
{
94 1
  # 0 index is title, the attribute to test against
95 1
  # message is our custom error msg
96 1
  # only run this validation on creation - not when updating
97 1
  static $validates_presence_of = array(
98 1
    array('title', 'message' => 'cannot be blank on a book!', 'on' => 'create')
99 1
  );
100 1
}
101 1
</code></pre>
102 1

                
103 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.
104 1

                
105 1
Available validations
106 1

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

                
109 1
* validates_presence_of
110 1
* validates_size_of
111 1
* validates_length_of
112 1
* validates_(in|ex)clusion_of
113 1
* validates_format_of
114 1
* validates_numericality_of
115 1
* validates_uniqueness_of
116 1
* validates_presence_of
117 1

                
118 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:
119 1

                
120 1
* message: default: *can't be blank*
121 1

                
122 1
<pre class="code"><code class="php">
123 1
class Book extends ActiveRecord\Model
124 1
{
125 1
  static $validates_presence_of = array(
126 1
    array('title'),
127 1
    array('cover_blurb', 'message' => 'must be present and witty')
128 1
  );
129 1
}
130 1
 
131 1
$book = new Book(array('title' => ''));
132 1
$book->save();
133 1
 
134 1
echo $book->errors->on('cover_blurb'); # => must be present and witty
135 1
echo $book->errors->on('title'); # => can't be blank
136 1
</code></pre>
137 1

                
138 1
validates_size_of / validates_length_of
139 1

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

                
142 1
is: attribute should be exactly n characters long
143 1
in/within: attribute should be within an range array(1,5)
144 1
maximum/minimum: attribute should not be above/below respectively
145 1
Each of the options has a particular message and can be changed.
146 1

                
147 1
is: uses key 'wrong_length'
148 1
in/within: uses keys 'too_long' & 'too_short'
149 1
maximum/minimum: uses keys 'too_long' & 'too_short'
150 1

                
151 1
<pre class="code"><code class="php">
152 1
class Book extends ActiveRecord\Model
153 1
{
154 1
  static $validates_size_of = array(
155 1
    array('title', 'within' => array(1,5), 'too_short' => 'too short!'),
156 1
    array('cover_blurb', 'is' => 20),
157 1
    array('description', 'maximum' => 10, 'too_long' => 'should be short and sweet')
158 1
  );
159 1
}
160 1
 
161 1
$book = new Book;
162 1
$book->title = 'War and Peace';
163 1
$book->cover_blurb = 'not 20 chars';
164 1
$book->description = 'this description is longer than 10 chars';
165 1
$ret = $book->save();
166 1
 
167 1
# validations failed so we get a false return
168 1
if ($ret == false)
169 1
{
170 1
  # too short!
171 1
  echo $book->errors->on('title');
172 1
 
173 1
  # is the wrong length (should be 20 chars)
174 1
  echo $book->errors->on('cover_blurb');
175 1
 
176 1
  # should be short and sweet
177 1
  echo $book->errors->on('description');
178 1
}
179 1
</code></pre>
180 1

                
181 1
validates_(in|ex)clusion_of
182 1

                
183 1
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:
184 1

                
185 1
in/within: attribute should/shouldn't be a value within an array
186 1
message: custom error message
187 1

                
188 1
<pre class="code"><code class="php">
189 1
class Car extends ActiveRecord\Model
190 1
{
191 1
  static $validates_inclusion_of = array(
192 1
    array('fuel_type', 'in' => array('hyrdogen', 'petroleum', 'bio-diesel', 'electric')),
193 1
  );
194 1
}
195 1
 
196 1
# this will pass since it's in the above list
197 1
$car = new Car(array('fuel_type' => 'electric'));
198 1
$ret = $car->save();
199 1
echo $ret # => true
200 1

                
201 1
class User extends ActiveRecord\Model
202 1
{
203 1
  static $validates_exclusion_of = array(
204 1
    array('password', 'in' => array('god', 'sex', 'password', 'love', 'secret'),
205 1
      'message' => 'should not be one of the four most used passwords')
206 1
  );
207 1
}
208 1
 
209 1
$user = new User;
210 1
$user->password = 'god';
211 1
$user->save();
212 1
echo $user->errors->on('password'); # => should not be one of the four most used passwords
213 1
</code></pre>
214 1

                
215 1
validates_format_of
216 1

                
217 1
This validation uses preg_match to verify the format of an attribute. You can create a regular expression to test against. Available options:
218 1

                
219 1
with: regular expression
220 1
message: custom error message
221 1

                
222 1
<pre class="code"><code class="php">
223 1
class User extends ActiveRecord\Model
224 1
{
225 1
  static $validates_format_of = array(
226 1
    array('email', 'with' =>
227 1
      '/^[^0-9][A-z0-9_]+([.][A-z0-9_]+)*[@][A-z0-9_]+([.][A-z0-9_]+)*[.][A-z]{2,4}$/')
228 1
    array('password', 'with' =>
229 1
      '/^.*(?=.{8,})(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).*$/', 'message' => 'is too weak')
230 1
  );
231 1
}
232 1
 
233 1
$user = new User;
234 1
$user->email = 'not_a_real_email.com';
235 1
$user->password = 'notstrong';
236 1
$user->save();
237 1
 
238 1
echo $user->errors->on('email'); # => is invalid
239 1
echo $user->errors->on('password'); # => is too weak
240 1
</code></pre>
241 1

                
242 1
validates_numericality_of
243 1

                
244 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:
245 1

                
246 1
only_integer: value must be an integer (e.g. not a float), message: "is not a number"
247 1
even, message: "must be even"
248 1
odd, message: "must be odd"
249 1
greater_than: >, message: "must be greater than %d"
250 1
greater_than_or_equal_to: >=, message: "must be greater than or equal to %d"
251 1
equal_to: ==, message: "must be equal to %d"
252 1
less_than: <, message: "must be less than %d"
253 1
less_than_or_equal_to: <=, message: "must be less than or equal to %d"
254 1

                
255 1
<pre class="code"><code class="php">
256 1
class Order extends ActiveRecord\Model
257 1
{
258 1
  static $validates_numericality_of = array(
259 1
    array('price', 'greater_than' => 0.01),
260 1
    array('quantity', 'only_integer' => true),
261 1
    array('shipping', 'greater_than_or_equal_to' => 0),
262 1
    array('discount', 'less_than_or_equal_to' => 5, 'greater_than_or_equal_to' => 0)
263 1
  );
264 1
}
265 1
 
266 1
$order = new Order;
267 1
$order->price = 0;
268 1
$order->quantity = 1.25;
269 1
$order->shipping = 5;
270 1
$order->discount = 2;
271 1
$order->save();
272 1
 
273 1
echo $order->errors->on('price'); # => must be greater than 0.01
274 1
echo $order->errors->on('quantity'); # => is not a number
275 1
echo $order->errors->on('shipping'); # => null
276 1
echo $order->errors->on('discount'); # => null
277 1
</code></pre>
278 1

                
279 1
validates_uniqueness_of
280 1

                
281 1
Tests whether or not a given attribute already exists in the table or not.
282 1

                
283 1
message: custom error message
284 1

                
285 1
<pre class="code"><code class="php">
286 1
class User extends ActiveRecord\Model
287 1
{
288 1
  static $validates_uniqueness_of = array(
289 1
    array('name'),
290 1
    array(array('blah','bleh'), 'message' => 'blah and bleh!')
291 1
  );
292 1
}
293 1
 
294 1
User::create(array('name' => 'Tito'));
295 1
$user = User::create(array('name' => 'Tito'));
296 1
$user->is_valid(); # => false
297 1
</code></pre>