1.0.1 • Published 4 years ago
com.siteblade.web.api.validation v1.0.1
com.siteblade.web.api.validation
This package provides field validation with messages connected to the NPM packages com.siteblade.intl, express and knex.
Examples
A validator specifies transformations and rules for fields.
import {
Validator, MinLength, MatchesField
} from 'com.siteblade.web.api.validation';
let [ value ] = await
new Validator({
// Use the knex package
knexInstance: undefined,
// NOTE
// Server applications generally must clone a default
// com.siteblade.intl.Translator.
translator: undefined,
fields: {
password: [
new MinLength(8),
new MatchesField('passwordconfirmation', {
message: 'validation.user.passwordsDoNotMatch',
}),
],
passwordconfirmation: [],
},
// Steps run after field rules.
steps: [
async (request, fields, report) => {
report('fieldname', 'validation.someError');
return { value: 'foo' };
},
async (request, fields, report, { value }) => {
console.log(value); // foo
return 50;
},
],
})
.validate(expressRequest, expressResponse);
// Example results:
//
// error = null;
// error.messages.fieldname = 'Message';
// If Validator.validate() omits the response argument,
// Validator.validate() returns [ value, messages ].
Custom rules
import { Rule } from 'com.siteblade.web.api.validation';
class ARule extends Rule {
constructor(options = {}) {
super(options);
}
async test(validator, fieldValues, value) {
// validator.knexInstance
return true;
}
formatError(translator) {
return translator.t(this.message);
}
}
Custom transforms
import { Transform } from 'com.siteblade.web.api.validation';
class ATransform extends Transform {
apply(value) {
return value;
}
}
1.0.1
4 years ago