@double-agent-validator/core
v12.0.2
Published
DoubleAgentValidator =======
Downloads
44
Keywords
Readme
DoubleAgentValidator
This package serves as complement to the java library called doubleagentvalidator.
This is a javascript library which allow to reuse the same json schemas used in the backend rest application to validates the data at the frontend.
This libs depends on:
Double Agent Validator dependencies:
How to test
npm run test
or, if using yarn
yarn test
How to build
npm run build
or, if using yarn
yarn build
How to use
1. Install the package in your application:
Install double-agent
npm install @double-agent-validator/core
2 Angular Setup
2.1 DoubleAgentAppModule
Create an AppDoubleAgentValidatorModule with a factory to get the validation script from the remote url and fill-in the DoubleAgentValidator service with the schemas, keywords and formats.
import { NgModule, APP_INITIALIZER } from '@angular/core';
import { ReactiveFormsModule } from '@angular/forms';
import { DoubleAgentValidatorV2Module, DoubleAgentValidator } from '@double-agent-validator/core';
import { environment } from '../environments/environment';
@NgModule({
imports: [
ReactiveFormsModule,
DoubleAgentValidatorV2Module.forRoot({
ajv: (self as any)['ajv'],
validationFn: (self as any)['validate']
}),
],
exports: [DoubleAgentValidatorV2Module],
providers: [
{
provide: APP_INITIALIZER,
useFactory: appInitializerFactory,
deps: [DoubleAgentValidator],
multi: true
}
]
})
export class DoubleAgentAppModule {
constructor() {
}
}
// This Factory would be used at application initialization process
// to load from local ou through http
export function appInitializerFactory(doubleAgentValidator: any) {
// initializaciton factory which will be called by Angular
return function () {
const promiseDoubleAgent = new Promise((resolve, reject) => {
const scriptAjvLoad = document.createElement('script');
// get the url from the environment object
scriptAjvLoad.src = environment.jsonSchemasLocalService;
scriptAjvLoad.onload = () => {
// after the load (onload) it will be ready to initialize the application
doubleAgentValidator.config['ajv'] = (window as any)['ajv'];
doubleAgentValidator.config['validationFn'] = (window as any)['validate'];
// resolves the promise, so the Angular application will bootstrap
resolve(null);
};
scriptAjvLoad.onerror = (error: any) => {
const errorMsg = 'Failed to load doubleAgentValidator' + error.message;
console.error(errorMsg);
// fails the Angular initialization
reject(errorMsg);
};
// adds the script element to the document body
// and so, the schema bundle will be parsed by the browser
document.body.appendChild(scriptAjvLoad);
});
return Promise.all([promiseDoubleAgent]);
};
}
2.2 Import the DoubleAgentAppModule in your AppModule
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import { ReactiveFormsModule } from '@angular/forms';
import { DoubleAgentAppModule } from './double-agent-appp-module';
@NgModule({
declarations: [AppComponent],
imports: [BrowserModule, ReactiveFormsModule, DoubleAgentAppModule],
providers: [],
bootstrap: [AppComponent],
})
export class AppModule {}
Great!!! You just did it, now the following services are available on your Angular > 12 App:
DoubleAgentValidatorService
This class allow you to validate some data in a service layer using its validate
method, which checks some data
againts an specific schema you pass to the service.
Your service will be something like the example bellow:
import { DoubleAgentValidator } from 'double-agent-validator';
import { ValidationResult } from 'double-agent-validator/models';
@Injectable()
class MyService {
constructor(private doubleAgentValidator: DoubleAgentValidator) {
}
validateContribuinte(): ValidationResult {
/***
// returns something like this
{
hasErrors: true;
errors: [
keyword: 'required',
dataPath: '.id',
message: 'field is missing'
];
}
*/
return this.doubleAgentValidator.validate('contribuinte-v1', data);
}
}
DoubleAgentFormGroupBuilder
This class can be used to build FormGroup containing the controls representing each property in the schema including the respective validators.
Example:
import { DoubleAgentFormGroupBuilder } from 'double-agent-validator';
import { FormGroup } from '@angular/forms';
@Component({
selector: 'my-form',
template: `
<form [formGroup]="formGroup">
<div class="form-group">
<label for="nome">Nome: </label>
<input type="text" id="nome" formControlName="nome">
</div>
<!-- your another controls for the others properties goes here too -->
</form>`
})
export class MyFormComponent {
private shemaName = 'contribuinte-v1';
private formGroup: FormGroup;
constructor(private doubleAgentFormGroupBuilder: DoubleAgentFormGroupBuilder) {
this.formGroup = doubleAgentFormGroupBuilder.build(this.schemaName);
}
}
If you want create formGroup without validators because your application will handle the validation process itself, you can do this:
import { DoubleAgentFormGroupBuilder } from 'double-agent-validator';
import { FormGroup } from '@angular/forms';
@Component({
selector: 'my-form',
template: `
<form [formGroup]="formGroup">
<div class="form-group">
<label for="nome">Nome: </label>
<input type="text" id="nome" formControlName="nome">
</div>
<!-- your another controls for the others properties goes here too -->
</form>`
})
export class MyFormComponent {
private shemaName = 'contribuinte-v1';
private formGroup: FormGroup;
constructor(private doubleAgentFormGroupBuilder: DoubleAgentFormGroupBuilder) {
this.formGroup = doubleAgentFormGroupBuilder.build(this.schemaName, {
createValidators: false
});
}
}
TODO
Provide the service to allow error messages mapping
Website to share the library api documentation