~coughphp/coughphp/2.0

« back to all changes in this revision

Viewing changes to docs/data_validation.markdown

  • Committer: Anthony Bush
  • Date: 2008-08-23 03:35:08 UTC
  • mfrom: (262.1.18 coughphp-release-1.3)
  • Revision ID: anthony@anthonybush.com-20080823033508-uy4yn5pmio6wcetv
Accept release-1.3 branch changes into trunk.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
Cough Data Validation
2
 
=====================
3
 
 
4
 
Cough will refuse to save your object if there are validation errors. By default, no data is invalidated. There are two ways to (in)validate data.
5
 
 
6
 
1. Inside the model
7
 
2. Outside the model
8
 
 
9
 
Validation Inside the Model
10
 
---------------------------
11
 
 
12
 
To validate data inside the model, add a validation function to the sub class named `doValidateData()` that accepts an array of data matching `[db_column_name] => [value]` and sets validation errors in `$this->validationErrors`. For example:
13
 
 
14
 
        protected function doValidateData(&$data) {
15
 
                if (empty($data['first_name'])) {
16
 
                        $this->validationErrors['first_name'] = 'First Name is required.';
17
 
                }
18
 
                if (empty($data['last_name'])) {
19
 
                        $this->validationErrors['last_name'] = 'Last Name is required.';
20
 
                }
21
 
                if (empty($data['email'])) {
22
 
                        $this->validationErrors['email'] = 'E-mail is required.';
23
 
                } else if ( ! Validator::isValidEmail($data['email'])) {
24
 
                        $this->validationErrors['email'] = 'Please enter a valid e-mail address.';
25
 
                } else if ($this->shouldInsert()) {
26
 
                        // Also check that the e-mail doesn't already exist in the database.
27
 
                        if ($this->isEmailTaken($data['email'])) {
28
 
                                $this->validationErrors['email'] = 'That e-mail is already registered.';
29
 
                        }
30
 
                }
31
 
                if (empty($data['password'])) {
32
 
                        $this->validationErrors['password'] = 'Please provide a password.';
33
 
                }
34
 
        }
35
 
 
36
 
In the above example, we check that some basic fields are specified (`first_name`, `last_name`, `email`, `password`) and that the `email` field is both a valid e-mail and, if we are performing an insert on save, that it doesn't already exist in the database.
37
 
 
38
 
Validation Outside the Model
39
 
----------------------------
40
 
 
41
 
Sometimes we need to validate data that won't actually be saved. For example, when we have the user enter their password twice we want to ensure they match but only save one. We can accomplish this by making calls to `invalidateField()`:
42
 
 
43
 
        $user->invalidateField('password', 'Passwords must match.');
44
 
 
45
 
Here is a full example using the above:
46
 
 
47
 
        $data = $_POST['User']; // data submitted by a registration form.
48
 
        $errors = array();      // no errors so far.
49
 
        $user = new User();
50
 
        $user->setFields($data);
51
 
        if ($data['password'] != $data['password_confirm']) {
52
 
                $user->invalidateField('password', 'Passwords must match.');
53
 
        }
54
 
        // save() will call the validate function even though we already
55
 
        // invalidated one field. This ensures we get all the error messages
56
 
        // from the model in addition to the above.
57
 
        if ( ! $user->save()) {
58
 
                if ( ! $user->isDataValid()) {
59
 
                        $errors = $user->getValidationErrors();
60
 
                }
61
 
        }
62
 
        // Pass errors on to the view, which can display them next to each field that had an error.
63
 
        $this->setViewVar('errors', $errors);
64
 
 
65
 
Note that we could also invalidate just the confirmation password field, even though the model won't save the password confirmation field. Validation is determined merely by whether or not validation errors exist, not whether or not they exist on the fields that would be saved. This allows you to have the error message stay with the appropriate field.
66
 
 
67
 
For example, it might make more sense to show the "Passwords must match" message next to the password confirmation field:
68
 
 
69
 
        if ($data['password'] != $data['password_confirm']) {
70
 
                $user->invalidateField('password_confirm', 'Passwords must match.');
71
 
        }
72
 
 
73
 
Or to show the message next to both fields:
74
 
 
75
 
        if ($data['password'] != $data['password_confirm']) {
76
 
                $user->invalidateField('password', 'Passwords must match.');
77
 
                $user->invalidateField('password_confirm', 'Passwords must match.');
78
 
        }
79
 
 
80
 
Other Validation Related Functions
81
 
----------------------------------
82
 
 
83
 
Cough's `save()` method calls `validateData()` which, if it hasn't been called before, calls `doValidateData()`. You can call `validateData()` yourself if you want to validate data before attempting a save. Just be sure to pass it the data to validate:
84
 
 
85
 
        $user->validateData($data);
86
 
        if ($user->isDataValid()) {
87
 
                // all good
88
 
                $user->save();
89
 
        } else {
90
 
                // one or more errors:
91
 
                $errors = $user->getValidationErrors();
92
 
        }
93
 
 
94
 
You can clear the errors in order to have `validateData()` run again:
95
 
 
96
 
        $user->clearValidationErrors();
97