| HTML-FormFu documentation | Contained in the HTML-FormFu distribution. |
HTML::FormFu::Constraint::MinMaxFields - Min/Max Multi-field Constraint
type: MinMaxFields
name: foo
others: [bar, baz]
min: 1
max: 1
Ensure that at least a minimum and only a maximum number of fields are present.
This constraint doesn't honour the not() value.
The maximum number of named fields which must be filled in.
The default for max is the number of all affected fields, in other words one more than the number of elements given to others.
Default Value: 1
Default Value: 0
Is a sub-class of, and inherits methods from HTML::FormFu::Constraint::_others, HTML::FormFu::Constraint
Mario Minati mario.minati@googlemail.com
This library is free software, you can redistribute it and/or modify it under the same terms as Perl itself.
| HTML-FormFu documentation | Contained in the HTML-FormFu distribution. |
package HTML::FormFu::Constraint::MinMaxFields; use Moose; use MooseX::Aliases; extends 'HTML::FormFu::Constraint'; with 'HTML::FormFu::Role::Constraint::Others'; has minimum => ( is => 'rw', alias => 'min', traits => ['Chained'], ); has maximum => ( is => 'rw', alias => 'max', traits => ['Chained'], ); after BUILD => sub { my $self = shift; $self->attach_errors_to_base(1); return; }; sub process { my ( $self, $params ) = @_; my $count = 0; # check when condition return if !$self->_process_when($params); # others are needed my $others = $self->others; return if !defined $others; # get field names to check my @names = ( $self->nested_name ); push @names, ref $others ? @{$others} : $others; # get min/max values my $min = defined $self->minimum ? $self->minimum : 1; my $max = defined $self->maximum ? $self->maximum : scalar @names; for my $name (@names) { my $value = $self->get_nested_hash_value( $params, $name ); if ( ref $value eq 'ARRAY' ) { my @errors = eval { $self->constrain_values( $value, $params ) }; if ( !@errors && !$@ ) { $count++; } } else { my $ok = eval { $self->constrain_value($value) }; if ( $ok && !$@ ) { $count++; } } } my $pass = ( $count < $min || $count > $max ) ? 0 : 1; return $self->mk_errors( { pass => $pass, failed => $pass ? [] : \@names, names => \@names, } ); } # return true if value is defined sub constrain_value { my ( $self, $value ) = @_; return 0 if !defined $value || $value eq ''; return 1; } __PACKAGE__->meta->make_immutable; 1; __END__