[Catalyst] Where should constraints go
Ian Docherty
ian at iandocherty.com
Fri Nov 3 14:40:13 GMT 2006
Where should the various constraint values go in my MVC structure? For
example the Model defines the size of each field in (for example) a
username field in the User database table as being 16 characters max.
I am using FormValidator to validate the username field by calling a
validation routine in the Model-User as you can see in the code snippets
below.
In the example of the username, the constraints are in the length (no
more than 16 characters) and in the 'existing' to ensure that a username
is not chosen that already exists.
This seems to make sense to me since it is the Model that knows the
constraints of the database. If I were to do other (business logic) type
constraints then I would probably put in a business logic layer where
these constraints were defined.
The problem is in the View. To give a text error message that 'Must be
between 1 and 16 characters' is hard-coding a constraint directly in the
view which would need to be changed if the database schema changed.
I cannot think of a 'clean' way of getting these database constraints
from the Model into the View.
Anybody else tackled this issue?
Regards
Ian
The Database has a constraint.
CREATE TABLE user (
id int(11) NOT NULL auto_increment,
firstname varchar(32),
lastname varchar(32),
username varchar(16),
...
In my FormValidator I have something like.
constraint_methods => {
user_username => [
{
name => 'length',
constraint =>
MyApp::Schema::User::validate_username_length(),
},
{
name => 'existing',
constraint =>
MyApp::Schema::User::validate_username_existing($c, $user),
},
],
The input form using TT is something like.
<tr>
<th align="right">Username</th>
<td align="left"><input type="text" size="44"
name="user_username" value="[% user.username %]"></td>
</td>
[% IF missing.user_username %]
<td align="left" class="error">Must not be blank</td>
[% ELSIF invalid.user_username.length %]
<td align="left" class="error">Must be between 1 and 16
characters</td>
[% ELSIF invalid.user_username.existing %]
<td align="left" class="error">Sorry, that username is already
taken</td>
[% END %]
</tr>
More information about the Catalyst
mailing list