[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: [cgiapp] Validation constraint



Jason Purdy wrote:
> Robert Hicks wrote:
> 
>> I am trying out the ValidateRM plugin. I have it working with one form
>> which is cool.
>>
>> The second form I have deals with hours worked on a project. The hours
>> are put in by increments of .25 (i.e. it could be .50 or 7.75). I know
>> I can check this with the mod ( % ) operator but I haven't a clue on
>> how to make that a constraint for the "total_hours" field to make sure
>> the user is putting in a valid number.
> 
> 
> My knee-jerk reaction is a customized subroutine to check that:
> 
> my $validation_profile = {
>     'constraints' => {
>       total_hours => {
>         constraint => 'is_quarter_hour'
>       },
>     },
>   };
> 
> sub is_quarter_hour {
>   my $result = 0;
>   my $data = shift;
> 
>   if ( $data % .25 ) {
>     $result = 1;
>   }
> 
>   return $result;
> }

I know it's untested, but you can't use % with non-integer numbers. I see 2
possible solutions, one regex based, the other using a subroutine (my example
shows the higher-order subroutines that the new DFV 4.0 likes).

REGEX
-----
my $profile = {
  constraint_methods => {
    total_hours =>  qr/^(\d*(\.((00?)|(25)|(50?)|(75))0*)?)$/,
  }
  ...
}

Now, this is less code, but it's not the most readable regex and would be a
maintenence problem if the business rule changes to allow tenth of an hour
increments, etc.

SUB
---
my $profile = {
  constraint_methods => {
    total_hours => hour_increment(.25),
  }
}

sub hour_increment {
    my $fraction = shift;
    return sub {
        my ($dfv, $value) = @_;
        my $result = $value / $fraction;
        # if the result is an integer
        if( $result == int ($result) ) {
            return $result;
        } else {
            return;
        }
    },
}

I like this method the best (besides my affinity for closures) it also allows
the business rule to change while minimizing the changes on your side. Just
change the .25 to .10 in the profile.

-- 
Michael Peters
Developer
Plus Three, LP


---------------------------------------------------------------------
Web Archive:  http://www.mail-archive.com/suppressed/
              http://marc.theaimsgroup.com/?l=cgiapp&r=1&w=2
To unsubscribe, e-mail: suppressed
For additional commands, e-mail: suppressed


Mail converted by mhonarc 2.6.15
This archive provided courtesy of JSW4.NET, Internet Hosting Services for Small Business.