2016-12-25 19:40:36 +00:00
|
|
|
# validate
|
2017-05-13 01:24:54 +00:00
|
|
|
[![version 1.0.2+4](https://img.shields.io/badge/pub-v1.0.2+4-brightgreen.svg)](https://pub.dartlang.org/packages/angel_validate)
|
2016-12-25 21:26:55 +00:00
|
|
|
[![build status](https://travis-ci.org/angel-dart/validate.svg)](https://travis-ci.org/angel-dart/validate)
|
|
|
|
|
2016-12-27 16:49:06 +00:00
|
|
|
[Live Example](https://angel-dart.github.io/validate)
|
2016-12-26 01:09:24 +00:00
|
|
|
|
2016-12-25 21:26:55 +00:00
|
|
|
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.
|
|
|
|
|
2016-12-26 01:09:24 +00:00
|
|
|
For convenience's sake, this library also exports `matcher`.
|
|
|
|
|
|
|
|
* [Examples](#examples)
|
|
|
|
* [Creating a Validator](#creating-a-validator)
|
|
|
|
* [Validating Data](#validating-data)
|
|
|
|
* [Required Fields](#required-fields)
|
2016-12-26 13:04:42 +00:00
|
|
|
* [Forbidden Fields](#forbidden-fields)
|
2016-12-26 01:09:24 +00:00
|
|
|
* [Default Values](#default-values)
|
|
|
|
* [Custom Validator Functions](#custom-validator-functions)
|
2016-12-26 13:04:42 +00:00
|
|
|
* [Auto-parsing Numbers](#autoparse)
|
2017-01-25 23:03:45 +00:00
|
|
|
* [Filtering Maps](#filter)
|
2016-12-26 13:04:42 +00:00
|
|
|
* [Custom Error Messages](#custom-error-messages)
|
2016-12-26 01:09:24 +00:00
|
|
|
* [Extending Validators](#extending-validators)
|
|
|
|
* [Bundled Matchers](#bundled-matchers)
|
|
|
|
* [Nested Validators](#nested-validators)
|
|
|
|
* [Use with Angel](#use-with-angel)
|
|
|
|
|
2016-12-25 21:26:55 +00:00
|
|
|
# Examples
|
|
|
|
|
|
|
|
## Creating a Validator
|
|
|
|
|
|
|
|
```dart
|
|
|
|
import 'package:angel_validate/angel_validate.dart';
|
|
|
|
|
|
|
|
main() {
|
|
|
|
var validator = new Validator({
|
|
|
|
'username': isAlphaNum,
|
2017-04-26 12:49:26 +00:00
|
|
|
'multiple,keys,with,same,rules': [isString, isNotEmpty],
|
2016-12-25 21:26:55 +00:00
|
|
|
'balance': [
|
|
|
|
greaterThanOrEqualTo(0),
|
|
|
|
lessThan(1000000)
|
2017-04-26 12:49:26 +00:00
|
|
|
],
|
|
|
|
'nested': [
|
|
|
|
foo,
|
|
|
|
[bar, baz]
|
2016-12-25 21:26:55 +00:00
|
|
|
]
|
|
|
|
});
|
|
|
|
}
|
|
|
|
```
|
|
|
|
|
|
|
|
## 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.
|
|
|
|
|
|
|
|
```dart
|
|
|
|
main() {
|
|
|
|
var result = validator.check(formData);
|
|
|
|
|
|
|
|
if (!result.errors.isNotEmpty) {
|
|
|
|
// Invalid data
|
|
|
|
} else {
|
|
|
|
// Safely handle filtered data
|
|
|
|
return someSecureOperation(result.data);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
```
|
|
|
|
|
|
|
|
You can `enforce` validation rules, and throw an error if validation fails.
|
|
|
|
|
|
|
|
```dart
|
|
|
|
main() {
|
|
|
|
try {
|
|
|
|
// `enforce` will return the filtered data.
|
|
|
|
var safeData = validator.enforce(formData);
|
|
|
|
} on ValidationException catch(e) {
|
|
|
|
print(e.errors);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
```
|
|
|
|
|
|
|
|
## 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.
|
|
|
|
|
|
|
|
```dart
|
|
|
|
main() {
|
|
|
|
var validator = new Validator({
|
2018-06-28 02:34:05 +00:00
|
|
|
'googleId*': isString,
|
|
|
|
|
|
|
|
// You can also use `requireField`
|
|
|
|
requireField('googleId'): isString,
|
2016-12-25 21:26:55 +00:00
|
|
|
});
|
|
|
|
}
|
|
|
|
```
|
|
|
|
|
2016-12-26 13:04:42 +00:00
|
|
|
## Forbidden Fields
|
|
|
|
To prevent a field from showing up in valid data, suffix it
|
|
|
|
with a `'!'`.
|
|
|
|
|
2016-12-25 21:26:55 +00:00
|
|
|
|
|
|
|
## Default values
|
|
|
|
|
|
|
|
If not present, default values will be filled in *before* validation.
|
|
|
|
This means that they can still be used with required fields.
|
|
|
|
|
|
|
|
```dart
|
|
|
|
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`](https://www.dartdocs.org/documentation/matcher/0.12.0%2B2/matcher/predicate.html).)
|
|
|
|
|
|
|
|
The function must *synchronously* return a `bool`.
|
|
|
|
|
|
|
|
```dart
|
|
|
|
main() {
|
|
|
|
var validator = new Validator({
|
|
|
|
'key*': (key) {
|
|
|
|
var file = new File('whitelist.txt');
|
|
|
|
return file.readFileSync().contains(key);
|
|
|
|
}
|
|
|
|
});
|
|
|
|
}
|
|
|
|
```
|
|
|
|
|
2016-12-26 13:04:42 +00:00
|
|
|
# Custom Error Messages
|
|
|
|
If these are not present, `angel_validate` will *attempt* to generate
|
|
|
|
a coherent error message on its own.
|
|
|
|
|
|
|
|
```dart
|
|
|
|
new Validator({
|
|
|
|
'age': [greaterThanOrEqualTo(18)]
|
|
|
|
}, customErrorMessages: {
|
|
|
|
'age': 'You must be an adult to see this page.'
|
|
|
|
});
|
|
|
|
```
|
2016-12-27 16:43:27 +00:00
|
|
|
The string `{{value}}` will be replaced inside your error message automatically.
|
2016-12-26 13:04:42 +00:00
|
|
|
|
|
|
|
# autoParse
|
|
|
|
Oftentimes, fields that we want to validate as numbers are passed as strings.
|
|
|
|
Calling `autoParse` will correct this before validation.
|
|
|
|
|
|
|
|
```dart
|
|
|
|
main() {
|
|
|
|
var parsed = autoParse({
|
|
|
|
'age': '34',
|
|
|
|
'weight': '135.6'
|
|
|
|
}, ['age', 'weight']);
|
|
|
|
|
|
|
|
validator.enforce(parsed);
|
|
|
|
}
|
|
|
|
```
|
|
|
|
|
|
|
|
You can also call `checkParsed` or `enforceParsed` as a shorthand.
|
|
|
|
|
2017-01-25 23:03:45 +00:00
|
|
|
# filter
|
|
|
|
This is a helper function to extract only the desired keys from a `Map`.
|
|
|
|
|
|
|
|
```dart
|
|
|
|
var inputData = {'foo': 'bar', 'a': 'b', '1': 2};
|
|
|
|
var only = filter(inputData, ['foo']);
|
|
|
|
|
|
|
|
print(only); // { foo: bar }
|
|
|
|
```
|
|
|
|
|
2016-12-25 21:26:55 +00:00
|
|
|
# Extending Validators
|
|
|
|
You can add situation-specific rules within a child validator.
|
2016-12-26 13:04:42 +00:00
|
|
|
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.
|
2016-12-25 21:26:55 +00:00
|
|
|
|
|
|
|
```dart
|
|
|
|
final Validator userValidator = new Validator({
|
|
|
|
'username': isString,
|
|
|
|
'age': [
|
|
|
|
isNum,
|
|
|
|
greaterThanOrEqualTo(18)
|
|
|
|
]
|
|
|
|
});
|
|
|
|
```
|
|
|
|
|
|
|
|
To mark a field as now optional, and no longer required,
|
|
|
|
suffix its name with a `'?'`.
|
|
|
|
|
|
|
|
```dart
|
|
|
|
var ageIsOptional = userValidator.extend({
|
|
|
|
'age?': [
|
|
|
|
isNum,
|
|
|
|
greaterThanOrEqualTo(13)
|
|
|
|
]
|
|
|
|
});
|
|
|
|
```
|
|
|
|
|
2016-12-26 01:36:59 +00:00
|
|
|
Note that by default, new validation rules are simply appended to
|
2016-12-25 21:26:55 +00:00
|
|
|
the existing list. To completely overwrite existing rules, set the
|
|
|
|
`overwrite` flag to `true`.
|
|
|
|
|
|
|
|
```dart
|
|
|
|
register(Map userData) {
|
|
|
|
var teenUser = userValidator.extend({
|
|
|
|
'age': lessThan(18)
|
|
|
|
}, overwrite: true);
|
|
|
|
}
|
|
|
|
```
|
|
|
|
|
|
|
|
# Bundled Matchers
|
|
|
|
This library includes some `Matcher`s for common validations,
|
|
|
|
including:
|
|
|
|
|
2016-12-26 13:04:42 +00:00
|
|
|
* `isAlphaDash`: Asserts that a `String` is alphanumeric, but also lets it contain dashes or underscores.
|
|
|
|
* `isAlphaNum`: Asserts that a `String` is alphanumeric.
|
2016-12-25 21:26:55 +00:00
|
|
|
* `isBool`: Asserts that a value either equals `true` or `false`.
|
2016-12-26 13:04:42 +00:00
|
|
|
* `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`.
|
2016-12-25 21:26:55 +00:00
|
|
|
* `isString`: Asserts that a value is a `String`.
|
2017-04-26 12:49:26 +00:00
|
|
|
* `isNonEmptyString`: Asserts that a value is a non-empty `String`.
|
2017-04-01 22:34:06 +00:00
|
|
|
* `isUrl`: Asserts that a `String` is an HTTPS or HTTP URL.
|
2016-12-25 21:26:55 +00:00
|
|
|
|
|
|
|
The remaining functionality is
|
|
|
|
[effectively implemented by the `matcher` package](https://www.dartdocs.org/documentation/matcher/0.12.0%2B2/matcher/matcher-library.html).
|
|
|
|
|
|
|
|
# Nested Validators
|
|
|
|
Very often, the data we validate contains other data within. You can pass
|
2016-12-26 01:09:24 +00:00
|
|
|
a `Validator` instance to the constructor, because it extends the
|
|
|
|
`Matcher` class.
|
2016-12-25 21:26:55 +00:00
|
|
|
|
|
|
|
```dart
|
|
|
|
main() {
|
|
|
|
var bio = new Validator({
|
2018-12-10 17:51:10 +00:00
|
|
|
'age*': [isInt, greaterThanOrEqualTo(0)],
|
|
|
|
'birthYear*': isInt,
|
2016-12-25 21:26:55 +00:00
|
|
|
'countryOfOrigin': isString
|
|
|
|
});
|
|
|
|
|
|
|
|
var book = new Validator({
|
|
|
|
'title*': isString,
|
|
|
|
'year*': [
|
|
|
|
isNum,
|
|
|
|
(year) {
|
|
|
|
return year <= new DateTime.now().year;
|
|
|
|
}
|
|
|
|
]
|
|
|
|
});
|
|
|
|
|
|
|
|
var author = new Validator({
|
|
|
|
'bio*': bio,
|
|
|
|
'books*': [
|
|
|
|
isList,
|
2016-12-26 01:09:24 +00:00
|
|
|
everyElement(book)
|
2016-12-25 21:26:55 +00:00
|
|
|
]
|
|
|
|
}, defaultValues: {
|
|
|
|
'books': []
|
|
|
|
});
|
|
|
|
}
|
|
|
|
```
|
|
|
|
|
|
|
|
# Use with Angel
|
|
|
|
|
2017-01-25 23:03:45 +00:00
|
|
|
`server.dart` exposes seven helper middleware:
|
2018-12-10 17:51:10 +00:00
|
|
|
* `validate(validator)`: Validates and filters `req.bodyAsMap`, and throws an `AngelHttpException.BadRequest` if data is invalid.
|
2016-12-25 21:26:55 +00:00
|
|
|
* `validateEvent(validator)`: Sets `e.data` to the result of validation on a service event.
|
2016-12-26 13:04:42 +00:00
|
|
|
* `validateQuery(validator)`: Same as `validate`, but operates on `req.query`.
|
2018-12-10 17:51:10 +00:00
|
|
|
* `autoParseBody(fields)`: Auto-parses numbers in `req.bodyAsMap`.
|
2016-12-26 13:04:42 +00:00
|
|
|
* `autoParseQuery(fields)`: Same as `autoParseBody`, but operates on `req.query`.
|
2018-12-10 17:51:10 +00:00
|
|
|
* `filterBody(only)`: Filters unwanted data out of `req.bodyAsMap`.
|
2017-01-25 23:03:45 +00:00
|
|
|
* `filterQuery(only)`: Same as `filterBody`, but operates on `req.query`.
|
2016-12-25 21:26:55 +00:00
|
|
|
|
|
|
|
```dart
|
|
|
|
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 {
|
2018-12-10 17:51:10 +00:00
|
|
|
res.write('You said: "${req.bodyAsMap["message"]}"');
|
2016-12-25 21:26:55 +00:00
|
|
|
});
|
|
|
|
|
|
|
|
app.service('api/todos')
|
|
|
|
..beforeCreated.listen(validateEvent(todo))
|
|
|
|
..beforeUpdated.listen(validateEvent(todo));
|
|
|
|
|
|
|
|
await app.startServer();
|
|
|
|
}
|
2017-01-31 12:22:45 +00:00
|
|
|
```
|