Here's the reason: I'm using Data::FormValidator to validate HTML form input. For those not familiar with this module, basically it allows you to pass in a validation profile which contains various "input specifications" that tell it how to validate your data. There is a "constraints" input specification which allows you to specify validation constraints, including coderefs, so no problem using length there (see the example below). However, there is also an input specification "constraint_regexp_map" which allows you to apply a constraint to any fields whose names match a supplied regex (also in the example below). Unfortunately, in this case, you cannot pass it a coderef -- only a regex or the name of a built-in (built into Data::FormValidator, that is) validation function.
Here's an example profile:
my $profile = {
index => {
required => [ qw(firstname surname address1 postcode email) ],
optional => [ qw(middlename address2 address3 address4) ],
constraints => {
postcode => '/^[A-Z]{1,2}\d[A-Z\d]?\s*\d[A-Z]{2}$/i',
email => {
constraint => sub {
return valid_email($_[0]) && length($_[0]) <= 100;
},
params => [ 'email' ],
},
constraint_regexp_map => {
'/name$/' => '/(?=^.{0,25}$)[[:print:]]*$/i',
'/^address/' => '/(?=^.{0,50}$)[[:print:]]*$/i',
},
},
};
So, the answer is probably 1) it's a poor design on the part of Data::FormValidator. I looked at the internals of Data::FormValidator, and I could patch it to accept coderefs, but at the time it was more work than I was willing to do. As in the example above, the "constraints" input specification allows you to supply both a coderef and a list of parameters, which have to be names of form fields. It then calls your coderef with the values of those fields as the parameters. In most cases, you would obviously want to pass it the name of the field to which the constraint applies, although it's not required.
I pondered adding support for backreferences within the names of the form fields, so you could have it match /^address(.*)$/ and then pass it "address$1" as a param. However, due to issues with scoping and eval and etc. and etc., I decided not to mess with a patch for now and just see if I could come up with a single matching regex. Hence the question.
-jehuni
|