angel_validate 1.0.4

  • Installing
  • Versions
  • 39


version 1.0.2+4 build status

Live Example

Validation library based on the matcher library, with Angel support. Why re-invent the wheel, when you can use the same validators you already use for tests?

This library runs both on the server, and on the client. Thus, you can use the same validation rules for forms on the server, and on the frontend.

For convenience's sake, this library also exports matcher.


Creating a Validator

import 'package:angel_validate/angel_validate.dart';

main() {
    var validator = new Validator({
        'username': isAlphaNum,
        'multiple,keys,with,same,rules': [isString, isNotEmpty],
        'balance': [
        'nested': [
            [bar, baz]

Validating data

The Validator will filter out fields that have no validation rules. You can rest easy knowing that attackers cannot slip extra data into your applications.

main() {
    var result = validator.check(formData);

    if (!result.errors.isNotEmpty) {
        // Invalid data
    } else {
        // Safely handle filtered data
        return someSecureOperation(;

You can enforce validation rules, and throw an error if validation fails.

main() {
    try {
        // `enforce` will return the filtered data.
        var safeData = validator.enforce(formData);
    } on ValidationException catch(e) {

Required Fields

Fields are optional by default.

Suffix a field name with a '*' to mark it as required, and to throw an error if it is not present.

main() {
    var validator = new Validator({
        'googleId*': isString,
        // You can also use `requireField`
        requireField('googleId'): isString,

Forbidden Fields

To prevent a field from showing up in valid data, suffix it with a '!'.

Default values

If not present, default values will be filled in before validation. This means that they can still be used with required fields.

final Validator todo = new Validator({
    'text*': isString,
    'completed*': isBool
}, defaultValues: {
    'completed': false

Default values can also be parameterless, synchronous functions that return a single value.

Custom Validator Functions

Creating a whole Matcher class is sometimes cumbersome, but if you pass a function to the constructor, it will be wrapped in a Matcher instance.

(It simply returns the value of calling predicate.)

The function must synchronously return a bool.

main() {
    var validator = new Validator({
        'key*': (key) {
            var file = new File('whitelist.txt');
            return file.readFileSync().contains(key);

Custom Error Messages

If these are not present, angel_validate will attempt to generate a coherent error message on its own.

new Validator({
    'age': [greaterThanOrEqualTo(18)]
}, customErrorMessages: {
    'age': 'You must be an adult to see this page.'

The string {{value}} will be replaced inside your error message automatically.


Oftentimes, fields that we want to validate as numbers are passed as strings. Calling autoParse will correct this before validation.

main() {
    var parsed = autoParse({
        'age': '34',
        'weight': '135.6'
    }, ['age', 'weight']);


You can also call checkParsed or enforceParsed as a shorthand.


This is a helper function to extract only the desired keys from a Map.

var inputData = {'foo': 'bar', 'a': 'b', '1': 2};
var only = filter(inputData, ['foo']);

print(only); // { foo: bar }

Extending Validators

You can add situation-specific rules within a child validator. You can also use extend to mark fields as required or forbidden that originally were not. Default value and custom error message extension is also supported.

final Validator userValidator = new Validator({
    'username': isString,
    'age': [

To mark a field as now optional, and no longer required, suffix its name with a '?'.

var ageIsOptional = userValidator.extend({
    'age?': [

Note that by default, new validation rules are simply appended to the existing list. To completely overwrite existing rules, set the overwrite flag to true.

register(Map userData) {
    var teenUser = userValidator.extend({
        'age': lessThan(18)
    }, overwrite: true);    

Bundled Matchers

This library includes some Matchers for common validations, including:

  • isAlphaDash: Asserts that a String is alphanumeric, but also lets it contain dashes or underscores.
  • isAlphaNum: Asserts that a String is alphanumeric.
  • isBool: Asserts that a value either equals true or false.
  • isEmail: Asserts that a String complies to the RFC 5322 e-mail standard.
  • isInt: Asserts that a value is an int.
  • isNum: Asserts that a value is a num.
  • isString: Asserts that a value is a String.
  • isNonEmptyString: Asserts that a value is a non-empty String.
  • isUrl: Asserts that a String is an HTTPS or HTTP URL.

The remaining functionality is effectively implemented by the matcher package.

Nested Validators

Very often, the data we validate contains other data within. You can pass a Validator instance to the constructor, because it extends the Matcher class.

main() {
    var bio = new Validator({
        'age*': [isInteger, greaterThanOrEqualTo(0)],
        'birthYear*': isInteger,
        'countryOfOrigin': isString

    var book = new Validator({
        'title*': isString,
        'year*': [
            (year) {
                return year <= new;

    var author = new Validator({
        'bio*': bio,
        'books*': [
    }, defaultValues: {
        'books': []

Use with Angel

server.dart exposes seven helper middleware:

  • validate(validator): Validates and filters req.body, and throws an AngelHttpException.BadRequest if data is invalid.
  • validateEvent(validator): Sets to the result of validation on a service event.
  • validateQuery(validator): Same as validate, but operates on req.query.
  • autoParseBody(fields): Auto-parses numbers in req.body.
  • autoParseQuery(fields): Same as autoParseBody, but operates on req.query.
  • filterBody(only): Filters unwanted data out of req.body.
  • filterQuery(only): Same as filterBody, but operates on req.query.
import 'package:angel_framework/angel_framework.dart';
import 'package:angel_validate/server.dart';

final Validator echo = new Validator({
    'message*': (String message) => message.length >= 5

final Validator todo = new Validator({
    'text*': isString,
    'completed*': isBool
}, defaultValues: {
    'completed': false

main() async {
    var app = new Angel();

    app.chain(validate(echo)).post('/echo', (req, res) async {
        res.write('You said: "${req.body["message"]}"');


    await app.startServer();


  • isNonEmptyString trims strings.
  • ValidationException extends AngelHttpException.
  • Added requireField and requireFields.

Use this package as a library

1. Depend on it

Add this to your package's pubspec.yaml file:

  angel_validate: ^1.0.4

2. Install it

You can install packages from the command line:

with pub:

$ pub get

Alternatively, your editor might support pub get. Check the docs for your editor to learn more.

3. Import it

Now in your Dart code, you can use:

import 'package:angel_validate/angel_validate.dart';
Version Uploaded Documentation Archive
1.0.4 Jun 28, 2018 Go to the documentation of angel_validate 1.0.4 Download angel_validate 1.0.4 archive
1.0.3 Nov 18, 2017 Go to the documentation of angel_validate 1.0.3 Download angel_validate 1.0.3 archive
1.0.2+4 May 13, 2017 Go to the documentation of angel_validate 1.0.2+4 Download angel_validate 1.0.2+4 archive
1.0.2+3 Apr 26, 2017 Go to the documentation of angel_validate 1.0.2+3 Download angel_validate 1.0.2+3 archive
1.0.2+2 Apr 26, 2017 Go to the documentation of angel_validate 1.0.2+2 Download angel_validate 1.0.2+2 archive
1.0.2+1 Apr 26, 2017 Go to the documentation of angel_validate 1.0.2+1 Download angel_validate 1.0.2+1 archive
1.0.2 Apr 26, 2017 Go to the documentation of angel_validate 1.0.2 Download angel_validate 1.0.2 archive
1.0.1 Mar 29, 2017 Go to the documentation of angel_validate 1.0.1 Download angel_validate 1.0.1 archive
1.0.0 Jan 25, 2017 Go to the documentation of angel_validate 1.0.0 Download angel_validate 1.0.0 archive
0.0.2 Dec 27, 2016 Go to the documentation of angel_validate 0.0.2 Download angel_validate 0.0.2 archive

All 15 versions...

Describes how popular the package is relative to other packages. [more]
Code health derived from static analysis. [more]
Reflects how tidy and up-to-date the package is. [more]
Weighted score of the above. [more]
Learn more about scoring.

The package version is not analyzed, because it does not support Dart 2. Until this is resolved, the package will receive a health and maintenance score of 0.

Analysis issues and suggestions

Fix dependencies in pubspec.yaml.

Running pub upgrade failed with the following output:

ERR: The current Dart SDK version is 2.0.0.
 Because angel_framework >=0.0.0-dev.1 <1.1.3 requires SDK version <2.0.0 and angel_framework >=1.1.3 <2.0.0-alpha depends on container ^0.1.2, angel_framework >=0.0.0-dev.1 <2.0.0-alpha requires container ^0.1.2.
 So, because container >=0.1.1 requires SDK version >=1.8.0 <2.0.0 and angel_validate depends on angel_framework ^1.0.0-dev, version solving failed.

Maintenance issues and suggestions

Fix platform conflicts. (-20 points)

Error(s) prevent platform classification:

Fix dependencies in pubspec.yaml.

The description is too short. (-20 points)

Add more detail about the package, what it does and what is its target use case. Try to write at least 60 characters.

Maintain an example. (-10 points)

Create a short demo in the example/ directory to show how to use this package. Common file name patterns include: main.dart, example.dart or you could also use angel_validate.dart.


Package Constraint Resolved Available
Direct dependencies
Dart SDK >=1.19.0 <3.0.0