frint-data-validation
Reactive data modelling package for Frint
Guide
Installation
With npm:
$ npm install --save frint-data frint-data-validation
Via unpkg CDN:
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/5.5.0/Rx.min.js"></script>
<script src="https://unpkg.com/frint-data@latest/dist/frint-data.min.js"></script>
<script src="https://unpkg.com/frint-data@latest/dist/frint-data-validation.min.js"></script>
<script>
</script>
Usage
Validation rules can be set in two ways using frint-data-validation
.
- Defining rules in Model classes statically
- Passing rules when calling the
validate()
function
Defining rules statically
Imagine we have a Post model with this schema:
import { Types, createModel } from 'frint-data';
const Post = createModel({
schema: {
title: Types.string,
},
});
We can now optionally add our validation rules as follows:
Post.validationRules = [
{
name: 'titleIsNotEmpty',
message: 'Title must not be empty',
rule: function (model) {
if (post.title.length === 0) {
return false;
}
return true;
}
}
];
Validating the model
To get the output of validation errors:
import { validate } from 'frint-data-validation';
const post = new Post({ title: '' });
const validationErrors = validate(post);
Since our title
is empty here, the validationErrors
will return this array:
console.log(validationErrors);
If there were no errors, validationErrors
would be an empty array.
Passing validation rules manually
You can also choose not to define the validation rules statically, and pass them when calling validate()
function:
import { validate } from 'frint-data-validation';
const post = new Post({ title: '' });
const validationErrors = validate(post, {
rules: [
{
name: 'titleIsNotEmpty',
message: 'Title must not be empty',
rule: model => model.title.length > 0,
},
],
});
Observing validation errors
If you want to keep observing the model for new errors as it keeps changing:
import { validate$ } from 'frint-data-validation';
const validationErrors$ = validate$(post);
Now the validationErrors$
observable can be subscribed, and it will emit an array with this structure:
[
{
name: string,
message: string,
}
]
API
validate
validate(model, options)
Arguments
model
(Model
): Model instance from frint-data
options
(Object
)options.rules
(Array
): Validation rules
Returns
Array
of validation errors.
validate$
validate$(model, options)
Reactive version of validate
function.
Returns
Observable
of validation errors.