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

Hello!

I'm using HTML::FormValidator to process an HTML form (which as been a very helpful module so far). One of the options is to use a custom constraint on a field-- check it's validity with your own subroutine. However, there aren't any examples in the docs, and it's not clear to me what this would look like, expecially if one wanted to pass multiple arguments to the routine. Someone care to share an example? Thanks!

-mark

  • Comment on Example of complex constraint with HTML::FormValidator

Replies are listed 'Best First'.
Re: Example of complex constraint with HTML::FormValidator
by buckaduck (Chaplain) on Mar 21, 2001 at 04:41 UTC
    In general, I'd try using something like:
    constraints => { myfield => { constraint => sub { return (checkField() ? 1 : 0) }, params => [qw(myfield, otherparam1, otherparam2)], }, ... }
    ...where you can either use a subroutine checkField() or replace it with a short test right there in the anonymous subroutine.

    There is an example in the documentation for the module, but it uses a built-in validation routine rather than an anonymous subroutine...

    buckaduck

Re: Example of complex constraint with HTML::FormValidator
by markjugg (Curate) on Mar 21, 2001 at 04:31 UTC
    I got it. It was combination of reading the docs more closely and translating them a bit. They say anonymous subroutine, but from reading the source code, it looks like a reference to a named subroutine will do as well. That gives me some more flexiblity. :) I think the constraint clause might look like this if I wanted to use a function called &customer that used two fields from the form, first_name and last_name to check the field field_to_check,:

    constraints => field_to_check => { constraint => \&custom, params => [ qw( first_name last_name) ], }, }

    -mark

      An anonymous subroutine means a reference to a subroutine. That reference may be constructed from a real one, or from one created on the fly.

      There is little one can do with normal subroutines that cannot be done by storing anonymous subroutines in variables and calling them indirectly. (Exceptions include special subroutines like AUTOLOAD, DESTROY, and import.) The converse is not true.

      Therefore while you may find constructing anonymous subroutines from normal ones to be more comfortable to think through, I doubt that they are actually more flexible.