Debian Codegraph @

README

raw
1 NAME
2 Data::Validate::Struct - Validate recursive Hash Structures
3
4 SYNOPSIS
5 use Data::Validate::Struct;
6 my $validator = new Data::Validate::Struct($reference);
7 if ( $validator->validate($config_hash_reference) ) {
8 print "valid\n";
9 }
10 else {
11 print "invalid " . $validator->errstr() . "\n";
12 }
13
14 DESCRIPTION
15 This module validates a config hash reference against a given hash
16 structure in contrast to Data::Validate in which you have to check each
17 value separately using certain methods.
18
19 This hash could be the result of a config parser or just any hash
20 structure. Eg. the hash returned by XML::Simple could be validated using
21 this module. You may also use it to validate CGI input, just fetch the
22 input data from CGI, map it to a hash and validate it.
23
24 Data::Validate::Struct uses some of the methods exported by
25 Data::Validate, so you need to install it too.
26
27 PREDEFINED BUILTIN DATA TYPES
28 int Match a simple integer number.
29
30 range(a-b)
31 Match a simple integer number in a range between a and b. Eg:
32
33 { loginport => 'range(22-23)' }
34
35 hex Match a hex value.
36
37 oct Match an octagonal value.
38
39 number
40 Match a decimal number, it may contain , or . and may be signed.
41
42 word
43 Match a single word, _ and - are tolerated.
44
45 line
46 Match a line of text - no newlines are allowed.
47
48 text
49 Match a whole text(blob) including newlines. This expression is very
50 loosy, consider it as an alias to any.
51
52 regex
53 Match a perl regex using the operator qr(). Valid examples include:
54
55 qr/[0-9]+/
56 qr([^%]*)
57 qr{\w+(\d+?)}
58
59 Please note, that this doesn't mean you can provide here a regex
60 against config options must match.
61
62 Instead this means that the config options contains a regex.
63
64 eg:
65
66 $cfg = {
67 grp = qr/root|wheel/
68 };
69
70 regex would match the content of the variable 'grp' in this example.
71
72 To add your own rules for validation, use the type() method, see
73 below.
74
75 uri Match an internet URI.
76
77 ipv4
78 Match an IPv4 address.
79
80 cidrv4
81 The same as above including cidr netmask (/24), IPv4 only, eg:
82
83 10.2.123.0/23
84
85 Note: shortcuts are not supported for the moment, eg:
86
87 10.10/16
88
89 will fail while it is still a valid IPv4 cidr notation for a network
90 address (short for 10.10.0.0/16). Must be fixed in Regex::Common.
91
92 ipv6
93 Match an IPv6 address. Some examples:
94
95 3ffe:1900:4545:3:200:f8ff:fe21:67cf
96 fe80:0:0:0:200:f8ff:fe21:67cf
97 fe80::200:f8ff:fe21:67cf
98 ff02:0:0:0:0:0:0:1
99 ff02::1
100
101 cidrv6
102 The same as above including cidr netmask (/64), IPv6 only, eg:
103
104 2001:db8:dead:beef::1/64
105 2001:db8::/32
106
107 quoted
108 Match a text quoted with single quotes, eg:
109
110 'barbara is sexy'
111
112 hostname
113 Match a valid hostname, it must qualify to the definitions in RFC
114 2396.
115
116 resolvablehost
117 Match a hostname resolvable via dns lookup. Will fail if no dns is
118 available at runtime.
119
120 path
121 Match a valid absolute path, it won't do a stat() system call. This
122 will work on any operating system at runtime. So this one:
123
124 C:\Temp
125
126 will return TRUE if running on WIN32, but FALSE on FreeBSD!
127
128 fileexists
129 Look if value is a file which exists. Does a stat() system call.
130
131 user
132 Looks if the given value is an existent user. Does a getpwnam()
133 system call.
134
135 group
136 Looks if the given value is an existent group. Does a getgrnam()
137 system call.
138
139 port
140 Match a valid tcp/udp port. Must be a digit between 0 and 65535.
141
142 vars
143 Matches a string of text containing variables (perl style variables
144 though) eg:
145
146 $user is $attribute
147 I am $(years) old
148 Missing ${points} points to succeed
149
150 MIXED TYPES
151 If there is an element which could match more than one type, this can be
152 matched by using the pipe sign "|" to separate the types.
153
154 { name => 'int | number' }
155
156 There is no limit on the number of types that can be checked for, and
157 the check is done in the sequence written (first the type 'int', and
158 then 'number' in the example above).
159
160 OPTIONAL ITEMS
161 If there is an element which is optional in the hash, you can use the
162 type 'optional' in the type. The 'optional' type can also be mixed with
163 ordinary types, like:
164
165 { name => 'text | optional' }
166
167 The type 'optional' can be placed anywhere in the type string.
168
169 NEGATIVE MATCHING
170 In some rare situations you might require a negative match. So a test
171 shall return TRUE if a particular value does NOT match the given type.
172 This might be usefull to prevent certain things.
173
174 To achieve this, you just have to prepend one of the below mentioned
175 types with the keyword no.
176
177 Example:
178
179 $ref = { path => 'novars' }
180
181 This returns TRUE if the value of the given config hash does NOT contain
182 ANY variables.
183
184 VALIDATOR STRUCTURE
185 The expected structure must be a standard perl hash reference. This hash
186 may look like the config you are validating but instead of real-live
187 values it contains types that define of what type a given value has to
188 be.
189
190 In addition the hash may be deeply nested. In this case the validated
191 config must be nested the same way as the reference hash.
192
193 Example:
194
195 $reference = { user => 'word', uid => 'int' };
196
197 The following config would be validated successful:
198
199 $config = { user => 'HansDampf', uid => 92 };
200
201 this one not:
202
203 $config = { user => 'Hans Dampf', uid => 'nine' };
204 ^ ^^^^
205 | |
206 | +----- is not a number
207 +---------------------- space not allowed
208
209 For easier writing of references you yould use a configuration file
210 parser like Config::General or Config::Any, just write the definition
211 using the syntax of such a module, get the hash of it and use this hash
212 as validation reference.
213
214 NESTED HASH STRUCTURES
215 You can also match against nested structures. Data::Validate::Struct
216 iterates into the given config hash the same way as the reference hash
217 looks like.
218
219 If the config hash doesn't match the reference structure, perl will
220 throw an error, which Data::Validate::Struct catches and returns FALSE.
221
222 Given the following reference hash:
223
224 $ref = {
225 'b1' => {
226 'b2' => {
227 'b3' => {
228 'item' => 'int'
229 }
230 }
231 }
232 }
233
234 Now if you validate it against the following config hash it will return
235 TRUE:
236
237 $cfg = {
238 'b1' => {
239 'b2' => {
240 'b3' => {
241 'item' => '100'
242 }
243 }
244 }
245 }
246
247 If you validate it for example against this hash, it will return FALSE:
248
249 $cfg = {
250 'b1' => {
251 'b2' => {
252 'item' => '100'
253 }
254 }
255 }
256
257 SUBROUTINES/METHODS
258 validate($config)
259 $config must be a hash reference you'd like to validate.
260
261 It returns a true value if the given structure looks valid.
262
263 If the return value is false (0), then the error message will be
264 written to the variable $!.
265
266 type(%types)
267 You can enhance the validator by adding your own rules. Just add one
268 or more new types using a simple hash using the type() method.
269 Values in this hash can be regexes or anonymous subs.
270
271 "type" does accept either a hash (%hash), a hash ref (%$hash) or a
272 list of key/values ("key => value") as input.
273
274 For details see "CUSTOM VALIDATORS".
275
276 debug()
277 Enables debug output which gets printed to STDERR.
278
279 errors
280 Returns an array ref with the errors found when validating the hash.
281 Each error is on the format '<value> doesn't match <types> at
282 <ref>', where <ref> is a comma separated tree view depicting where
283 in the the error occured.
284
285 errstr()
286 Returns the last error, which is useful to notify the user about
287 what happened. The format is like in "errors".
288
289 EXPORTED FUNCTIONS
290 add_validators
291 This is a class function which adds types not per object but globally
292 for each instance of Data::Validate::Struct.
293
294 use Data::Validate::Struct qw(add_validators);
295 add_validators( name => .. );
296 my $v = Data::Validate::Struct->new(..);
297
298 Parameters to add_validators are the same as of the type method.
299
300 For details see "CUSTOM VALIDATORS".
301
302 CUSTOM VALIDATORS
303 You can add your own validators, which maybe regular expressions or
304 anonymous subs. Validators can be added using the type() method or
305 globally using the add_validators() function.
306
307 CUSTOM REGEX VALIDATORS
308 If you add a validator which is just a regular expressions, it will
309 evaluated as is. This is the most simplest way to customize validation.
310
311 Sample:
312
313 use Data::Validate::Struct qw(add_validators);
314 add_validators(address => qr(^\w+\s\s*\d+$));
315 my $v = Data::Validate::Struct->new({place => 'address'});
316 $v->validate({place => 'Livermore 19'});
317
318 Regexes will be executed exactly as given. No flags or ^ or $ will be
319 used by the module. Eg. if you want to match the whole value from
320 beginning to the end, add ^ and $, like you can see in our 'address'
321 example above.
322
323 CUSTOM VALIDATOR FUNCTIONS
324 If the validator is a coderef, it will be executed as a sub.
325
326 Example:
327
328 use Data::Validate::Struct qw(add_validators);
329 add_validators(
330 list => sub {
331 my $list = shift;
332 my @list = split /\s*,\s*/, $list;
333 return scalar @list > 1;
334 },
335 );
336
337 In this example we add a new type 'list', which is really simple. 'list'
338 is a subroutine which gets called during evaluation for each option
339 which you define as type 'list'.
340
341 Such a subroutine must return a true value in order to produce a match.
342 It receives the following arguments:
343
344 * value to be evaluated
345
346 * unparsed arguments, if defined in the reference
347
348 * array of parsed arguments, tokenized by , and -
349
350 That way you may define a type which accepts an arbitrary number of
351 arguments, which makes the type customizable. Sample:
352
353 # new validator
354 $v4 = Data::Validate::Struct->new({ list => nwords(4) });
355
356 # define type 'nwords' with support for 1 argument
357 $v4->type(
358 nwords => sub {
359 my($val, $ignore, $count) = @_;
360 return (scalar(split /\s+/, $val) == $count) ? 1 : 0;
361 },
362 );
363
364 # validate
365 $v4->validate({ list => 'these are four words' });
366
367 CUSTOM VALIDATORS USING A GRAMMAR
368 Sometimes you want to be more flexible, in such cases you may use a
369 parser generator to validate input. This is no feature of
370 Data::Validate::Struct, you will just write a custom code ref validator,
371 which then uses the grammar.
372
373 Here's a complete example using Parse::RecDescent:
374
375 use Parse::RecDescent;
376 use Data::Validate::Struct qw(add_validators);
377
378 my $grammar = q{
379 line: expr(s)
380 expr: number operator number
381 number: int | float
382 int: /\d+/
383 float: /\d*\\.\d+/
384 operator: '+' | '-' | '*' | '/'
385 };
386
387 my $parse = Parse::RecDescent->new($grammar);
388
389 add_validators(calc => sub { defined $parse->line($_[0]) ? 1 : 0; });
390
391 my $val = Data::Validate::Struct->new({line => 'calc'});
392
393 if ($val->validate({line => "@ARGV"})) {
394 my $r;
395 eval "\$r = @ARGV";
396 print "$r\n";
397 }
398 else {
399 print "syntax error\n";
400 }
401
402 Now you can use it as follows:
403
404 ./mycalc 54 + 100 - .1
405 153.9
406
407 ./mycalc 8^2
408 syntax error
409
410 NEGATED VALIDATOR
411 A negative/reverse match is automatically added as well, see "NEGATIVE
412 MATCHING".
413
414 EXAMPLES
415 Take a look to t/run.t for lots of examples.
416
417 CONFIGURATION AND ENVIRONMENT
418 No environment variables will be used.
419
420 SEE ALSO
421 I recommend you to read the following documentations, which are supplied
422 with perl:
423
424 perlreftut Perl references short introduction.
425
426 perlref Perl references, the rest of the story.
427
428 perldsc Perl data structures intro.
429
430 perllol Perl data structures: arrays of arrays.
431
432 Data::Validate common data validation methods.
433
434 Data::Validate::IP common data validation methods for IP-addresses.
435
436 LICENSE AND COPYRIGHT
437 Copyright (c) 2007-2015 T. v.Dein
438
439 This library is free software; you can redistribute it and/or modify it
440 under the same terms as Perl itself.
441
442 BUGS AND LIMITATIONS
443 Some implementation details as well as the API may change in the future.
444 This will no more happen if entering a stable release (starting with
445 1.00).
446
447 To submit use <http://rt.cpan.org>.
448
449 INCOMPATIBILITIES
450 None known.
451
452 DIAGNOSTICS
453 To debug Data::Validate::Struct use debug() or the perl debugger, see
454 perldebug.
455
456 For example to debug the regex matching during processing try this:
457
458 perl -Mre=debug yourscript.pl
459
460 DEPENDENCIES
461 Data::Validate::Struct depends on the module Data::Validate,
462 Data::Validate:IP, Regexp::Common, File::Spec and File::stat.
463
464 AUTHORS
465 T. v.Dein <tlinden |AT| cpan.org>
466
467 Per Carlson <pelle |AT| cpan.org>
468
469 Thanks to David Cantrell for his helpful hints.
470
471 VERSION
472 0.10
473