1 package Blog
::Validator
;
6 my ( $class, $params ) = @_;
8 my $self = bless { params
=> $params, fields
=> {}, errors
=> {} }, $class;
20 $self->{ fields
} ||= {};
22 $self->{ fields
} = { %{ $self->{ fields
} }, @_ };
26 my ( $self, $field, $error ) = @_;
31 $self->{ errors
}->{ $field } ||= [];
33 push @
{ $self->{ errors
}->{ $field } }, $error;
38 return $self->{ errors
}->{ $field };
44 return $self->{ errors
};
52 #die Dumper($self->{ fields });
54 $self->clean_params();
57 while ( my ( $field, $value ) = each %{ $self->{ fields
} } ) {
58 if ( !defined $self->param( $field ) || $self->param( $field ) eq '' ) {
59 $self->error( $field, 'Required' ) if $value->{ required
};
64 while ( my ( $rule, $arg ) = each %$value ) {
65 next RULE
if $rule eq 'required';
66 my $method = "check_$rule";
67 if ( $self->can( $method ) ) {
68 $self->$method( $field, $arg );
73 #die Dumper $self->errors;
75 return keys %{ $self->errors } ?
0 : 1;
79 my ( $self, $name ) = @_;
83 return $self->{ fields
}->{ $name };
87 my ( $self, $name ) = @_;
91 return $self->{ params
}->{ $name };
97 return $self->{ params
};
103 foreach my $param ( keys %{ $self->params } ) {
104 delete $self->{ params
}->{ $param }
105 unless exists $self->{ fields
}->{ $param };
110 my ( $self, $name, $re ) = @_;
112 $self->error( $name, 'Invalid input' )
113 unless $self->param( $name ) =~ $re;
117 my ( $self, $name, $email ) = @_;
119 $self->error( $name, 'Invalid email' )
120 unless $self->param( $name ) =~ m/^([0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\w]*[0-9a-zA-Z]?\.)+[a-zA-Z]{2,9})$/;
124 my ( $self, $name, $in ) = @_;
126 $self->error( $name, 'Invalid input' )
127 unless grep { $self->param( $name ) eq $_ } @
$in;
136 This library is free software, you can redistribute it and/or modify
137 it under the same terms as Perl itself.