• Stars
    star
    36
  • Rank 729,975 (Top 15 %)
  • Language
    Perl
  • License
    Other
  • Created almost 14 years ago
  • Updated about 5 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Type constraints based data validator for Perl5

NAME

Data::Validator - Rule based validator on type constraint system

VERSION

This document describes Data::Validator version 1.07.

SYNOPSIS

use 5.10.0;
use Data::Validator;

# for functions
sub get {
    state $rule = Data::Validator->new(
        uri        => { isa => 'Str', xor => [qw(schema host path_query)] },

        schema     => { isa => 'Str', default => 'http' },
        host       => { isa => 'Str' },
        path_query => { isa => 'Str', default => '/' },

        method     => { isa => 'Str', default => 'GET' },
    );

    my $args = $rule->validate(@_);
    # ...
}
get( uri => 'http://example.com/' );

# for methods
sub method {
    state $rule = Data::Validator->new(
        foo => 'Str',
    )->with('Method');

    my($self, $args) = $rule->validate(@_);
    # ...
}
Foo->method( foo => 'bar' );



# using sequenced parameters
sub seq {
    state $rule = Data::Validator->new(
        foo => 'Str',
    )->with('StrictSequenced');

    my $args = $rule->validate(@_);
    # ...
}
seq( 'bar' );          # seq() will get { foo => 'bar' }
seq({ foo => 'bar' }); # named style are NOT available!



# using Method and StrictSequenced together
sub seq_method {
    state $rule = Data::Validator->new(
        foo => 'Str',
    )->with( 'Method', 'StrictSequenced');

    my($self, $args) = $rule->validate(@_);
    # ...
}
Foo->seq_method( 'bar' ); # seq_method() will get { foo => 'bar' }



# using sequenced and named parameters
sub smart_seq {
    my $rule = Data::Validator->new(
        r1 => 'Str',
        r2 => 'HashRef',  # accept this
        o1 => { isa => 'Str', default => 'yes' },
        o2 => { isa => 'Num', optional => 1 },
    )->with('SmartSequenced');

    my $args = $rule->validate(@_);
    # ...
}

# all will get { r1 => 'foo', r2 => { val => 'bar' }, o1 => 'yes' }

# mixed style(recommend)
smart_seq( 'foo', { val => 'bar' }, { o1 => 'yes' } );
smart_seq( 'foo', { val => 'bar' } );

# also accept sequenced style
smart_seq( 'foo', { val => 'bar' }, 'yes' );
smart_seq( 'foo', { val => 'bar' } );

# also accept named style
smart_seq( { r1 => 'foo', r2 => { val => 'bar' }, o1 => 'yes' } );
smart_seq( { r1 => 'foo', r2 => { val => 'bar' } } );

DESCRIPTION

This is yet another validation library, based on Smart::Args but less smart.

This is designed for general data validation. For example, it is useful for CSV, JSON, XML, and so on.

Concepts

  • Natural as Perl code

    I love Smart::Args because it is really stylish, but it does not seem Perl-ish.

    Thus, I have designed Data::Validator in more Perl-ish way with full of Smart::Args functionality.

  • Basics on type constraint system

    Moose's type constraint system is awesome, and so is Mouse's. In fact, Mouse's type constraints are much faster than Moose's so that you need not hesitate to check types.

    Thus, I have made Data::Validator on Mouse's type constraint system.

  • Pure Perl

    Although I do not hesitate to depend on XS modules, some people think that XS modules are hard to install.

    Thus, I have written Data::Validator in pure Perl and selected dependent modules which work in pure Perl.

  • Performance

    Validators should be as fast as possible because they matter only for illegal inputs. Otherwise, one would want something like no validation option.

    This is much faster than Params::Validate, which has an XS backend, though.

INTERFACE

Data::Validator->new( $arg_name => $rule [, ...]) :Validator

Creates a validation rule. You should cache the rules for performance.

Attributes for $rule are as follows:

  • isa => $type : Str|Object

    The type of the rule, which can be a Mouse type constraint name, a class name, or a type constraint object of either Mouse or Moose (i.e. it's duck-typed).

  • does => $role : Str|Object

    The type of the rule, which can be a Mouse type constraint name, a role name, or a type constraint object of either Mouse or Moose (i.e. it's duck-typed).

    Note that you cannot use it with the isa attribute.

  • coerce => $should_coercion : Bool

    If false, the rule does not try to coerce when the validation fails. Default to true.

  • default=> $value : Any | CodeRef

    The default value for the argument. If it is a CODE reference, it is called in scalar context as $default->($validator, $rule, $args) and its return value is used as a default value.

    Because arguments are validated in the order of definitions, default callbacks can rely on the previously-filled values:

      my $v = Data::Validator->new(
          foo => { default => 99 },
          bar => { default => sub {
              my($validator, $this_rule, $args) = @_;
              return $args->{foo} + 1;
          } },
      );
      $v->validate();          # bar is 100
      $v->validate(foo => 42); # bar is 43
    

    Unlike Moose/Mouse's default, any references are allowed, but note that they are statically allocated.

  • optional => $value : Bool

    If true, users can omit the argument. Default to false.

  • xor => $exclusives : ArrayRef

    Exclusive arguments, which users cannot pass together.

  • documentation => $doc : Str

    Descriptions of the argument.

    This is not yet used anywhere.

$validator->find_rule($name :Str)

Finds the rule named $name. Provided for error handling.

$validator->with(@extensions) :Validator

Applies @extensions to $validator and returns itself.

See "EXTENSIONS" for details.

$validator->validate(@args) :HashRef

Validates @args and returns a restricted HASH reference.

Restricted hashes are hashes which do not allow to access non-existing keys, so you must check a key exists in the hash before fetching its values.

EXTENSIONS

There are extensions which changes behaviours of validate().

Method

Takes the first argument as an invocant (i.e. class or object instance), and returns it as the first value:

my($invocant, $args) = $rule->validate(@_);

SmartSequenced

Deals with arguments in mixing sequenced style and named style. The sequenced style should be passed by the order of argument rules, and the named style arguments should be the last argument as HASH ref.

The typical usage is that the required arguments as sequenced style, and some optional arguments as named style.

StrictSequenced

Deals with arguments in sequenced style, where users should pass arguments by the order of argument rules, instead of by-name.

Note that single HASH ref argument was dealt as named-style arguments, but this feature is NOT available since version 1.01.

Sequenced

Deals with arguments in sequenced style, where users should pass arguments by the order of argument rules, instead of by-name.

Note that if the last argument is a HASH reference, it is regarded as named-style arguments.

AllowExtra

Regards unknown arguments as extra arguments, and returns them as a list of name-value pairs:

my($args, %extra) = $rule->validate(@_);

NoThrow

Does not throw errors. Instead, it provides validators with the errors attribute:

my $args = $v->validate(@_); # it never throws errors
if($v->has_errors) {
    my $errors = $v->clear_errors;
    foreach my $e(@{$errors}) {
        # $e has 'type', 'message' and 'name'
        print $e->{message}, "\n";
    }
}

Croak

Does not report stack backtrace on errors, i.e. uses croak() instead of confess() to throw errors.

NoRestricted

Does not make the argument hash restricted.

DEPENDENCIES

Perl 5.8.1 or later.

BUGS

All complex software has bugs lurking in it, and this module is no exception. If you find a bug please either email me, or add the bug to cpan-RT.

SEE ALSO

Smart::Args

Params::Validate

Sub::Args

MooseX::Params::Validate

Mouse

Hash::Util for a restricted hash.

AUTHOR

Fuji, Goro (gfx) [email protected]

LICENSE AND COPYRIGHT

Copyright (c) 2010, Fuji Goro (gfx). All rights reserved.

This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself.

More Repositories

1

Swift-PureJsonSerializer

a pure-Swift JSON serializer and deserializer
Swift
113
star
2

universal-zopfli-js

JavaScript binding to Zopfli with WebAssembly.
TypeScript
79
star
3

Android-Helium

Material Hatena bookmark reader for Android
HTML
68
star
4

docker-android-project

DEPRECATED because Android SDK license does not allow re-distribution of its binaries
59
star
5

graphql-blog

"「GraphQL」徹底入門 ─ RESTとの比較、API・フロント双方の実装から学ぶ" のサンプルコード
Ruby
53
star
6

android-power-assert-plugin

Power Assert for Android
Groovy
46
star
7

Android-EncryptUtils

[obosolete] Encypted SharedPreferences
Java
43
star
8

android-oss-best-practices

Best practices on creating Android OSS library projects [JA]
32
star
9

perl.js

emscripten build settings for perl
JavaScript
31
star
10

WatchRaptor

Chrome extension to watch GitHub CI status changes
TypeScript
29
star
11

ruby-regexp_trie

Fast keyword matching with the Trie algorithm (a Ruby port of Perl's Regexp::Trie)
Ruby
28
star
12

swift-words

Swift訳語集
23
star
13

isucon7-qualify

SugyaburoX repo for ISUCON7 qualify, 2017/10/22 (Sun)
JavaScript
21
star
14

rack-devfavicon

A rack middleware to show gray-scaled favicon on development
Ruby
18
star
15

example-github-actions-with-tty

A demo repository to prepare TTY for GitHub Actions step scripts
16
star
16

gradle-android-utils

Java
14
star
17

Dist-Maker

Yet another distribution maker
Perl
14
star
18

hello-bpf-core

An example app for BPF CO-RE and CI settings with GitHub Actions
C
14
star
19

gradle-plugin-template

A template project for Gradle plugins
Groovy
13
star
20

Swift-MultiThreading

A demo code for synchronization in Swift
Swift
13
star
21

OrmaWithKotlin

Example Kotlin app for Orma
Kotlin
12
star
22

example-updating-wiki-with-gha

An example repository to update wiki pages in a GitHub Actions workflow
JavaScript
12
star
23

hj

A command line tool to convert HTTP/1 style text to JSON
Rust
11
star
24

swift-resources

List of Resources on the Swift programming language
11
star
25

Perl-Module-Install-XSUtil

Support XS-based modules in the term of Module::Install
Perl
10
star
26

Acme-Perl-VM

A Perl5 Virtual Machine in Pure Perl
Perl
10
star
27

p5-POSIX-AtFork

Perl5 interfafce to pthread_atfork()
Perl
10
star
28

AndroidLocationClientExample

Java
9
star
29

LambdaAndroid

Shell
9
star
30

App-test-travis

Simulates Travis-CI environments
Perl
9
star
31

go-visual_width

Handles Unicode East Asian Width in Golang
Go
9
star
32

p5-Acme-Hidek

Happy birthday hidek!
Perl
8
star
33

TinyPdfReader

An example for tiny book readers for Android
Java
8
star
34

source-map-inspector

source map visualization
JavaScript
8
star
35

mousex-getopt

IMPORTANT: Call for maintainers!
Perl
8
star
36

RxJavaExample

Java
7
star
37

Swift-SwiftEither

A PoC of an ideal error handling in Swift
Swift
7
star
38

require-simple.js

node.js-like require() for browsers
JavaScript
7
star
39

p5-Types

Type constraint framework for Perl5
Perl
7
star
40

Perl-Enumerable

Perl
7
star
41

typescript-rtti

PoC of TypeScript RTTI with custom transformers that use ts.TypeChecker
TypeScript
7
star
42

Perl-PerlIO-Util

PerlIO::Util on CPAN
Perl
7
star
43

JSX-Hacking-Guide

Memories of a possible future...
6
star
44

Perl-MooseToMouse

Any::Moose::Convert @ CPAN
Perl
6
star
45

Android-BoltsExample

Java
6
star
46

Java-WeakIdentityHashMap

A standalone library for WeakIdentityHashMap to implement inside-out fields
Java
6
star
47

norejs

CLI interface to JavaScriptCore with node-like environment
C
6
star
48

p5-Test-LeakTrace

Test::LeakTrace on CPAN
Perl
6
star
49

tiscript

Turing-Incomplete TypeScript as a Configuration Language
Rust
6
star
50

ltsv-query

Analyzes LTSV logs with SQL
Perl
6
star
51

Android-HankeiN

Location Memos on the Map
Java
6
star
52

dart-shooting

A dart port of @tkihira's HTML5 shooting game
JavaScript
5
star
53

clion.js

JavaScript
5
star
54

p5-Data-Clone

Polymorphic data cloning
Perl
5
star
55

Xslate-Sandbox

Xslate sandbox service
Perl
5
star
56

Android-SNS-SignIn

Java
5
star
57

Perl-Data-Util

Data::Util @ CPAN
Perl
4
star
58

android-builtin-resource

Show android.R.drawable.*
Java
4
star
59

Web-Weaver

Library for PSGI requests
Perl
4
star
60

Perl-optimizer-hotspot

A hotspot optimizer for Perl
Perl
4
star
61

p5-lib-xi

Installs missing library on demand
Perl
4
star
62

Keyword-Boolean

Introduce boolean keywords for perl 5.11.2
Perl
4
star
63

proguard-retrace.js

TypeScript
4
star
64

cpp-rope-test

C++
4
star
65

Perl-namespace-clean-xs

Perl
4
star
66

Perl-MouseX-MethodAttributes

This module is experimental and won't be released unless someone takes over the maintenance.
Perl
4
star
67

visual_width.rb

Ruby Implementation of East Asian Width
Ruby
4
star
68

hello-typescript-2021

JavaScript
4
star
69

LLEval-Client

Interface to dankogai's LLEval service
Perl
3
star
70

dart-sessionstorage

An example to make use of WebStorage
Dart
3
star
71

p5-MouseX-Foreign

Allows Mouse classes inherit from foreign classes (i.e. non-Mouse classes)
Perl
3
star
72

github-actions-showcase

A set of examples for GitHub Actions
Perl
3
star
73

Android-LevelDBExample

Java
3
star
74

Service-DiffNotify

Notify file diffs in a directory
Perl
3
star
75

Swift-StringFormat

This is EXPERIMENTAL. Do not use it.
Swift
3
star
76

jslexer.js

Tiny JavaScript tokenizer
JavaScript
3
star
77

YAPC-Asia-2009-gfx

Documents and Data of YAPC::Asia 2009
Perl
3
star
78

Requires.PL

Perl
3
star
79

p5-Benchmark-Memory

Measures memory usage of Perl code snippets
Perl
3
star
80

gfx.github.io

JavaScript
3
star
81

p5-Plack-Handler-CLI

Command line interface to PSGI applications
Perl
3
star
82

java-codemodel-example

An example to generate Java source code with CodeModel
Groovy
3
star
83

GoogleMapV2Example

An example application for Google Maps Android API v2
Java
3
star
84

Perl5-ShipIt-Step-ChangeAllVersions

Updates versions in all the modules
Perl
3
star
85

p5-MouseX-Traits

MooseX::Traits equivalent in Mouse
Perl
3
star
86

p5-FurlX-Coro

Multiple HTTP requests with Coro
Perl
3
star
87

bluesky-rss-bot

RSS bot for Bluesky in Rust
Rust
3
star
88

Perl-macro

macro.pm @ CPAN
Perl
2
star
89

BinSearch-demo

Benchmark binary search algorithm against linear search algorithm
Perl
2
star
90

golang-interpreter

Very simple golang interpreter
2
star
91

docker-android-project-with-emulator

This does NOT work yet
Shell
2
star
92

Remotoris

Perl
2
star
93

p5-Scope-Ban

Perl
2
star
94

stdio-open_memstream

C
2
star
95

ecp-slack-command-rust

Slack app to servie an echo command in Fastly Compute@Edge
Rust
2
star
96

dart-frogrun

Compile a dart program with frogc and run it with node
2
star
97

Android-JavassistExample

Groovy
2
star
98

cpp-fast-strtox

C
2
star
99

Android-Hello-RubyMotion

Ruby
2
star
100

gradle-android-eggbox-plugin

Eggbox, eggs in a box!
Groovy
2
star