[Catalyst] "Best Practice" for validating form input

Perrin Harkins perrin at elem.com
Thu Aug 25 23:38:23 CEST 2005


On Thu, 2005-08-25 at 15:42 -0400, Kevin Old wrote:
> Thanks for the example above.  I am implementing this too, and was
> wondering if you have any code showing how you display $form->msgs.  I
> see they are a hash of <span> tags, but wondering if there was another
> option in displaying them other than just looping through the hash and
> printing the <span>'s.

We turn them into keys to be used to retrieve messages from a
Class::Phrasebook file.

This is some code to change a D::FV error about an invalid first_name
field into the string first_name_invalid:

sub _errs_to_messages {
    my ($self, $errs) = @_;

    foreach my $field_name ( sort keys %{$errs} ) {
        # decode error type from value set
        my $value = $errs->{$field_name};
        my $error_type;
        if ($value =~ /missing/i) {
            $error_type = 'missing';
        } elsif ($value =~ /invalid/i) {
            $error_type = 'invalid';
        } else {
            croak("Unknown error type for field '$field_name' value
'$value'");
        }

        # add a message for the error
        add_message("${field_name}_$error_type", from_module => ref
($self));
    }
}

> Specifically, I'd like to have the <span> placed beside the field that
> had the problem.

For this, we use background colors to highlight the invalid or missing
fields.  For example:
<input name="first_name" type="text" value="" style="width:
200px;<tmpl_if err_first_name> background-color: #ffe66b;</tmpl_if>" />

(We set err_${field_name} for each of the D::FV errors.)

> One thing I thought about is using some JS to add
> the <span> after the element with the error.

You should be able to get your template to do that.

- Perrin





More information about the Catalyst mailing list