nmerriweather has asked for the wisdom of the Perl Monks concerning the following question:

I've written a custom form class to handle making & validating forms.

usage:
my $form = new FormObject( $ref2QuestionsHash, $ref2QuestionsOrderArra +y ); $form->printForm; $form->validate($ref2UserInput)
i'm working out the validation of select boxes right now -- I want only the selectbox options to be valid.

Options are assigned to a selectbox using an array of value/text pairs as follows:
'data' => [ ['m','male'], ['f','female'], ],
That would result in html of : _option value="m"_ male _/option_ -- and an f/female

Validating this, right now, happens as follows:
my $valid = 0; for (my $i=0; $i<=$#{$question->{'data'}};$i++){ if ( $answer eq ${$question->{'data'}}[$i][0] ) { $valid = 1; last; } }
So, my question is - anyone have a better idea? The only other option I considered was creating a hash of acceptable answers and checking existance -- but to accomplish that I'd either have to pre-compute the hash keys, which saves me looping at the expense of memory, OR i'd loop through it realtime to make the hash -- which this method does already without the added step of checking the hash

Replies are listed 'Best First'.
Re: web form processing - efficiency question
by blokhead (Monsignor) on May 07, 2004 at 00:26 UTC
    I'm not sure I understand your reservations about hashes, or what you mean by "precomputing hash keys" and extra memory.

    The only thing you lose by moving to a hash is the ordering of the keys, but you can get that back:

    my $question = { descriptions => { m => "male", f => "female", o => "other" }, choices => [ qw/m f o/ ] }
    Then to generate the HTML in the right order is not so bad (not that I'm a big fan of this -- you should be using a templating system anyway):
    for my $choice ( @{ $question->{choices} } ) { my $text = $question->{descriptions}{$choice}; print qq[<option value="$choice">$text</option>\n]; }
    And validating choices becomes trivial:
    $valid = exists $question->{descriptions}{$answer};
    Anyway, having an array of arrays, with inner arrays having just 2 items, is a good sign that a hash (or certainly a relation matrix) might be in order.

    blokhead

      I never thought of that approach -- i'm going to give that a shot.

      I severly disliked every templating system I came across in the past few weeks -- so I decided to build my own. The only part i questioned so far was html select fields.
        did you also check out Template-Magic? its very simple to use and very flexible.

        for the form-data validation must of us use Data::FormValidator which is mature.
        ciao
        philipp