@tictuk/json-field-schema-validation
v1.4.0
Published
JSON Field Schema Validation
Readme
JSON Field Schema Validation Package
Installation (using as a package)
npm install @tictuk/json-field-schema-validationUsing from a web browser
Create the bundle files
npm run bundleMake the bundle files available from the Tictuk CDN
Upload these files from the project directory to S3:
Source Files
./node_modules/joi/dist/joi-browser.min.js./dist/@tictuk/json-field-schema-validation@<VERSION>.jse.g../dist/@tictuk/[email protected]
Target Directories
- (production)
S3: cdn.tictuk.com/webviewFlow/orgForms/ - (development)
S3: cdn.tictuk.com/webviewFlow_staging/orgForms/
Validators
required
The field value is required (i.e. value cannot be empty).
Fulfilled by joi base rule: required
NOTE: if this is property is present, regardless of it's value, the "required" rule will be enforced.
rules: {
required: true
}The field value must be an email address.
Fulfilled by joi base rule: email
NOTE: Top level domain email address (e.g. name@tld) is not allowed.
rules: {
email: true
}min
The field value must be a numeric value and greater than or equal to the min value
Fulfilled by joi base rule: min
rules: {
min: 20
}max
The field value must be a numeric value and less than or equal to the max value
Fulfilled by joi base rule: max
rules: {
max: 20
}minLength
The field value's length must be greater than or equal to the minLength value
Fulfilled by joi base rule: min
rules: {
minLength: 5
}maxLength
The field value's length must be less than or equal to the maxLength value
Fulfilled by joi base rule: max
rules: {
maxLength: 10
}alphanum
The field value must contain only alphanumeric values
Fulfilled by joi string rule: alphanum
rules: {
alphanum: true
}allowed
The field value must be in an array of allowed values
Fulfilled by joi base rule: valid
rules: {
allowed: ["AA", "BB", "CC"]
}cpf
The field value must be a Brazil CPF value
Custom rule
rules: {
cpf: { type: 'custom' }
}numeric
The field value must contain only numeric digits
Custom rule
rules: {
numeric: { type: 'custom' }
}fixedLength
The field value's length must be equal to an allowedLength
Custom rule
rules: {
fixedLength: { type: 'custom', ruleValue: 5 }
}rules: {
fixedLength: { type: 'custom', ruleValue: [6,8] }
}Usage
Simple Example
- Validate a single schema field
import {
InputSchema,
Lang,
ValidateSchemaParams,
Values,
FieldPick,
validateSchema,
} from '@tictuk/json-field-schema-validation';
const schema: InputSchema = {
fields: [
{
name: 'fiscalNumber',
label: {
en_US: 'Fiscal Number',
pt_PT: 'Número Fiscal',
},
validation: {
rules: {
required: true,
minlength: 3,
},
},
},
{
name: 'brazilCPF',
label: {
en_US: 'CPF',
pt_PT: 'CPF',
},
validation: {
rules: {
cpf: {
type: 'custom',
},
},
messages: {
'cpf.default': {
en_US: 'I told ya valid cpf',
pt_PT: 'I told ja validao cpf',
},
},
},
},
],
validation: {
messages: {
internalServerError: {
pt_PT: 'Internal Server Error',
en_US: 'Internal Server Error',
},
stringEmpty: {
pt_PT: '%label% is required',
en_US: '%label% is required',
},
stringBase: {
pt_PT: '%label% must be a valid string',
en_US: '%label% must be a valid string',
},
numberBase: {
pt_PT: '%label% must be a number',
en_US: '%label% must be a number',
},
objectUnknown: {
pt_PT: '%label% is not allowed',
en_US: '%label% is not allowed',
},
anyInvalid: {
pt_PT: '%label% contains an invalid value',
en_US: '%label% contains an invalid value',
},
anyRequired: {
pt_PT: '%label% is required',
en_US: '%label% is required',
},
stringEmail: {
pt_PT: '%label% must be a valid email',
en_US: '%label% must be a valid email',
},
stringMin: {
pt_PT: '%label% must be at least %limit% characters long',
en_US: '%label% must be at least %limit% characters long',
},
stringMax: {
pt_PT: '%label% must be less than or equal to %limit% characters long',
en_US: '%label% must be less than or equal to %limit% characters long',
},
numberMin: {
pt_PT: '%label% must be greater than or equal to %limit%',
en_US: '%label% must be greater than or equal to %limit%',
},
numberMax: {
pt_PT: '%label% must be less than or equal to %limit%',
en_US: '%label% must be less than or equal to %limit%',
},
validCPF: {
pt_PT: 'Por favor indique o CPF válido',
en_US: 'Please enter a valid CPF number',
},
},
},
};
const values: Values = {
brazilCPF: '12345678909',
};
const lang: Lang = 'pt';
const pick: FieldPick = ['brazilCPF'];
const validateSchemaParams: ValidateSchemaParams = {
schema,
values,
lang,
pick,
};
const validateSchemaResponse = await validateSchema(validateSchemaParams);
if (!validateSchemaResponse.valid) {
console.error('Error! Message: ' + validateSchemaResponse.errorMessage);
return false;
}
return true;Simplistic Example
- Validate a single schema field
- Only check valid status
- Not supply error messages
import {
InputSchema,
Lang,
ValidateSchemaParams,
Values,
FieldPick,
validateSchema,
} from '@tictuk/json-field-schema-validation';
const schema: InputSchema = {
fields: [
{
name: 'fiscalNumber',
label: {
en_US: 'Fiscal Number',
pt_PT: 'Número Fiscal',
},
validation: {
rules: {
required: true,
minlength: 3,
},
},
},
{
name: 'brazilCPF',
label: {
en_US: 'CPF',
pt_PT: 'CPF',
},
validation: {
rules: {
cpf: {
type: 'custom',
},
},
},
},
],
};
const values: Values = {
brazilCPF: '12345678909',
};
const lang: Lang = 'pt';
const pick: FieldPick = ['brazilCPF'];
const validateSchemaParams: ValidateSchemaParams = {
schema,
values,
lang,
pick,
};
const validateSchemaResponse = await validateSchema(validateSchemaParams);
return !!validateSchemaResponse.valid;Complex Example
- Validate all schema fields at once
- Supply error messages in multiple languages
- Filter for different kinds of errors
- Use returned property
value - Use optional
satisfieskeyword on the values and params (when the values are known in compile time) to access values by property name on the response.
import {
InputSchema,
Lang,
ValidateSchemaParams,
Values,
validateSchema,
} from '@tictuk/json-field-schema-validation';
const schema: InputSchema = {
fields: [
{
name: 'fiscalName',
label: {
en_US: 'Fiscal Name',
es_ES: 'Nombre',
pt_PT: 'Nome',
},
validation: {
rules: {
required: true,
minlength: 0,
},
},
},
{
name: 'fiscalNumber',
label: {
en_US: 'Fiscal Number',
es_ES: 'Cedula o RUC',
pt_PT: 'Número Fiscal',
},
validation: {
rules: {
required: true,
minlength: 3,
},
},
},
{
name: 'email',
label: {
en_US: 'Email',
es_ES: 'Correo Electrónico',
pt_PT: 'Correio Eletrônico',
},
validation: {
rules: {
required: true,
email: true,
},
},
},
{
name: 'phone',
label: {
en_US: 'Phone',
es_ES: 'Teléfono',
pt_PT: 'Telefone',
},
validation: {
rules: {
required: true,
minlength: 3,
},
messages: {
required: {
en_US: 'Please enter your phone number',
pt_PT: 'Desculpe escriba su numerao de telefono',
es_ES: 'Por favor escriba su número de teléfono',
},
minlength: {
en_US: 'I told ya at least 3 chars',
pt_PT: 'I told ja ato leastao 3 chares',
es_ES: 'I told ja ato leasto 3 chares',
},
},
},
},
{
name: 'ID',
label: {
en_US: 'I.D.',
pt_PT: 'IDDñ',
},
validation: {
rules: {
number: true,
min: 10000000,
max: 999999999,
},
},
},
],
validation: {
messages: {
internalServerError: {
pt_PT: 'Internal Server Error',
es_ES: 'Error interno del servidor',
en_US: 'Internal Server Error',
},
stringEmpty: {
pt_PT: '%label% is required',
es_ES: '%label% es obligatorio',
en_US: '%label% is required',
},
stringBase: {
pt_PT: '%label% must be a valid string',
es_ES: '%label% debe ser una cadena de texto válida',
en_US: '%label% must be a valid string',
},
numberBase: {
pt_PT: '%label% must be a number',
es_ES: '%label% debe ser un número válido',
en_US: '%label% must be a number',
},
objectUnknown: {
pt_PT: '%label% is not allowed',
es_ES: '%label% no está permitido',
en_US: '%label% is not allowed',
},
anyInvalid: {
pt_PT: '%label% contains an invalid value',
es_ES: '%label% contiene un valor no válido',
en_US: '%label% contains an invalid value',
},
anyRequired: {
pt_PT: '%label% is required',
es_ES: '%label% es obligatorio',
en_US: '%label% is required',
},
stringEmail: {
pt_PT: '%label% must be a valid email',
es_ES: '%label% debe ser una dirección de correo electrónico válida',
en_US: '%label% must be a valid email',
},
stringMin: {
pt_PT: '%label% must be at least %limit% characters long',
es_ES: '%label% debe tener al menos %limit% caracteres',
en_US: '%label% must be at least %limit% characters long',
},
stringMax: {
pt_PT: '%label% must be less than or equal to %limit% characters long',
es_ES:
'%label% debe tener menos de %label% caracteres o %limit% caracteres como máximo',
en_US: '%label% must be less than or equal to %limit% characters long',
},
numberMin: {
pt_PT: '%label% must be greater than or equal to %limit%',
es_ES: '%label% debe ser mayor o igual que %limit%',
en_US: '%label% must be greater than or equal to %limit%',
},
numberMax: {
pt_PT: '%label% must be less than or equal to %limit%',
es_ES: '%label% debe ser menor o igual que %limit%',
en_US: '%label% must be less than or equal to %limit%',
},
validCPF: {
pt_PT: 'Por favor indique o CPF válido',
es_ES: 'Por favor ingresa un npumero de CPF válido',
en_US: 'Please enter a valid CPF number',
},
},
},
};
const values = {
fiscalName: 'abc',
fiscalNumber: 'xyz',
email: '[email protected]',
phone: '123',
} satisfies Values; // Optional: can also specify type as Values
const lang: Lang = 'es';
const validateSchemaParams = {
schema,
values,
lang,
} satisfies ValidateSchemaParams; // Optional: can also specify type as ValidateSchemaParams
const validateSchemaResponse = await validateSchema(validateSchemaParams);
if (!validateSchemaResponse.valid) {
if (validateSchemaResponse.error instanceof ValidationError) {
console.error('Error in validation: ' + validateSchemaResponse.error);
} else {
console.error('Internal error: ' + validateSchemaResponse.error);
}
return validateSchemaResponse.errorMessage;
}
for (const [key, value] of Object.entries(validateSchemaResponse.value)) {
//...
}
console.log(validateSchemaResponse.value.fiscalName);
return validateSchemaResponse.value;