Recent comments and posts model methods. Tags cloud. Post modtime fix.
[blog.pm.git] / lib / Blog / Validator.pm
blob0b2b05476873db38befa0901338a95b2836743b5
1 package Blog::Validator;
3 use strict;
5 sub new {
6 my ( $class, $params ) = @_;
8 my $self = bless { params => $params, fields => {}, errors => {} }, $class;
10 $self->init_fields();
12 return $self;
15 sub init_fields { }
17 sub add_fields {
18 my $self = shift;
20 $self->{ fields } ||= {};
22 $self->{ fields } = { %{ $self->{ fields } }, @_ };
25 sub error {
26 my ( $self, $field, $error ) = @_;
28 return unless $field;
30 if ( $error ) {
31 $self->{ errors }->{ $field } ||= [];
33 push @{ $self->{ errors }->{ $field } }, $error;
35 return;
38 return $self->{ errors }->{ $field };
41 sub errors {
42 my ( $self ) = @_;
44 return $self->{ errors };
47 sub is_valid {
48 my ( $self ) = @_;
50 #use Data::Dumper;
52 #die Dumper($self->{ fields });
54 $self->clean_params();
56 FIELD:
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 };
60 next FIELD;
63 RULE:
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;
78 sub field {
79 my ( $self, $name ) = @_;
81 return unless $name;
83 return $self->{ fields }->{ $name };
86 sub param {
87 my ( $self, $name ) = @_;
89 return unless $name;
91 return $self->{ params }->{ $name };
94 sub params {
95 my ( $self ) = @_;
97 return $self->{ params };
100 sub clean_params {
101 my ( $self ) = @_;
103 foreach my $param ( keys %{ $self->params } ) {
104 delete $self->{ params }->{ $param }
105 unless exists $self->{ fields }->{ $param };
109 sub check_re {
110 my ( $self, $name, $re ) = @_;
112 $self->error( $name, 'Invalid input' )
113 unless $self->param( $name ) =~ $re;
116 sub check_email {
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})$/;
123 sub check_in {
124 my ( $self, $name, $in ) = @_;
126 $self->error( $name, 'Invalid input' )
127 unless grep { $self->param( $name ) eq $_ } @$in;
130 =head1 AUTHOR
134 =head1 LICENSE
136 This library is free software, you can redistribute it and/or modify
137 it under the same terms as Perl itself.
139 =cut