summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--lib/TUWF/Validate.pm5
-rw-r--r--t/validate.t7
2 files changed, 12 insertions, 0 deletions
diff --git a/lib/TUWF/Validate.pm b/lib/TUWF/Validate.pm
index adeb1d6..f7b0aa4 100644
--- a/lib/TUWF/Validate.pm
+++ b/lib/TUWF/Validate.pm
@@ -62,6 +62,11 @@ our %default_validations = (
# error object to ensure that.
+{ type => 'scalar', func => sub { $_[0] =~ $reg ? 1 : { regex => "$reg", got => $_[0] } } }
},
+ enum => sub {
+ my @l = ref $_[0] eq 'HASH' ? sort keys %{$_[0]} : ref $_[0] eq 'ARRAY' ? @{$_[0]} : ($_[0]);
+ my %opts = map +($_,1), @l;
+ +{ type => 'scalar', func => sub { $opts{ (my $v = $_[0]) } ? 1 : { expected => \@l, got => $_[0] } } }
+ },
minlength => _length(sub { $_[0] >= $_[1] }),
maxlength => _length(sub { $_[0] <= $_[1] }),
diff --git a/t/validate.t b/t/validate.t
index ffecb7b..82f979d 100644
--- a/t/validate.t
+++ b/t/validate.t
@@ -116,6 +116,13 @@ t { type => 'hash', length => 1, unknown => 'accept' }, {qw/1 a 2 b/}, {qw/1 a 2
t { type => 'hash', length => 1, keys => {a => {required=>0}, b => {required=>0}} }, {a=>1}, {a=>1}, undef;
t { regex => '^a' }, 'abc', 'abc', undef; # XXX: Can't use qr// here because t() does dclone(). The 'hex' test covers that case anyway.
t { regex => '^a' }, 'cba', 'cba', { validation => 'regex', regex => '^a', got => 'cba' };
+t { enum => [1,2] }, 1, 1, undef;
+t { enum => [1,2] }, 2, 2, undef;
+t { enum => [1,2] }, 3, 3, { validation => 'enum', expected => [1,2], got => 3 };
+t { enum => 1 }, 1, 1, undef;
+t { enum => 1 }, 2, 2, { validation => 'enum', expected => [1], got => 2 };
+t { enum => {a=>1,b=>2} }, 'a', 'a', undef;
+t { enum => {a=>1,b=>2} }, 'c', 'c', { validation => 'enum', expected => ['a','b'], got => 'c' };
t { anybool => 1 }, 1, 1, undef;
t { anybool => 1 }, undef, 0, undef;
t { anybool => 1 }, '', 0, undef;