Model validation
Here we'll talk about the content of the @banquette/model-validation
package.
Its content is at the crossroad between the @banquette/model
and @banquette/validation
packages.
The goal of this package is to avoid making them inter-dependent.
This package is very light and only contains a decorator and a service.
@Assert
@Assert
is a decorator you can put on the properties of your models to validate them:
import { Assert } from '@banquette/model-validation';
import { NotEmpty } from '@banquette/validation';
class Article {
@Assert(NotEmpty())
public title: string;
}
You can then validate it manually using the validate
utility function:
import { validate } from '@banquette/model-validation';
const result = validate(new Article());
// Returns a ValidationResult
TIP
If you build a form using the transformers, the validators set using @Assert
will automatically be added to the corresponding form components.
Metadata
The @Assert
decorator is just a shortcut to registering a validator for a given couple constructor/attribute.
But you could do it manually:
import { Injector } from '@banquette/dependency-injection';
import { ModelValidationMetadataService } from '@banquette/model-validation';
import { NotEmpty } from '@banquette/validation';
const metadata = Injector.Get(ModelValidationMetadataService);
metadata.register(Article, 'title', NotEmpty());
TIP
A use case for this could be to validate an object literal (on which you can't add decorators).
But the real value of this service is that it centralizes the validators of a model so any module can access it.
That's for example how the validators are automatically assigned when a form is created by transforming a model.
To get the validator of a model property:
const validator: ValidatorInterface|null = metadata.get('ModelIdentifier', 'propertyName');
TIP
The model identifier can be a constructor or an alias.