@jsarc/jon
v0.0.1
Published
JON est une bibliothèque TypeScript conçue pour la validation et la gestion des schémas de données. Elle offre une solution robuste pour valider les types de données, gérer les erreurs, et supporter une variété de types de données complexes.
Readme
@jsarc/jon
@jsarc/jon est une bibliothèque TypeScript conçue pour la validation et la gestion des schémas de données. Elle offre une solution robuste pour valider les types de données, gérer les erreurs, et supporter une variété de types de données complexes.
✨ Fonctionnalités Principales
📝 Validation de Schéma
- Types de données variés : String, Number, Boolean, Date, Enum, Array, Object, File, etc.
- Gestion intelligente des erreurs : Messages d'erreur personnalisables et support multi-langue.
- Validation flexible : Règles de validation personnalisées pour chaque type de données.
🌐 Intégration Facile
- Utilisation simple : Intégration facile avec les applications web et Node.js.
- Support des navigateurs : Compatible avec les navigateurs modernes.
📦 Installation
Via npm/yarn/pnpm
npm install @jsarc/jon
# ou
yarn add @jsarc/jon
# ou
pnpm add @jsarc/jonImportation directe (CDN)
<script src="@jsarc/jon/jon.all.js"></script>🚀 Utilisation
Importation des Schémas
import {
StringSchema,
NumberSchema,
BooleanSchema,
DateSchema,
EnumSchema,
NotEnumSchema,
ArraySchema,
ObjectSchema,
FileSchema
} from '@jsarc/jon';Exemples de Validation
Validation de String
const stringSchema = new StringSchema({ minLength: 5, maxLength: 10 });
const result = stringSchema.validate("Bonjour");
console.log(result.valid); // true ou falseValidation de Number
const numberSchema = new NumberSchema({ min: 0, max: 100 });
const result = numberSchema.validate(50);
console.log(result.valid); // true ou falseValidation de Boolean
const booleanSchema = new BooleanSchema();
const result = booleanSchema.validate(true);
console.log(result.valid); // true ou falseValidation de Date
const dateSchema = new DateSchema();
const result = dateSchema.validate(new Date());
console.log(result.valid); // true ou falseValidation de Enum
const enumSchema = new EnumSchema(["valeur1", "valeur2", "valeur3"]);
const result = enumSchema.validate("valeur1");
console.log(result.valid); // true ou falseValidation de Array
const arraySchema = new ArraySchema({ minItems: 1, maxItems: 5 });
const result = arraySchema.validate([1, 2, 3]);
console.log(result.valid); // true ou falseValidation de Object
const objectSchema = new ObjectSchema({
name: new StringSchema({ minLength: 2 }),
age: new NumberSchema({ min: 0 })
});
const result = objectSchema.validate({ name: "Alice", age: 30 });
console.log(result.valid); // true ou falseValidation de File
const fileSchema = new FileSchema({ allowedExtensions: ["pdf", "docx"] });
const result = fileSchema.validate(new File(["contenu"], "fichier.pdf"));
console.log(result.valid); // true ou falseStructure du Projet
@jsarc/jon/
├── jon.all.js
├── jon.all.min.js
├── index.d.ts
├── index.js
├── index.min.d.ts
├── index.min.js
├── package.json
├── tsconfig.json
└── README.md📜 Licence
Ce projet est sous licence MIT. Voir le fichier LICENSE pour plus de détails.
📄 Démonstrations
🔤 String (Chaîne de caractères)
// Vérification du type string
const value = "billy chaud";
const schema = (new JON.String(lang)).label('string1');
schema.validate(value);
// Vérification du type string - Echec
const value = [];
const schema = (new JON.String(lang)).label('string1');
schema.validate(value);
// Vérification du type string
const value = "billy chaud";
const schema = (new JON.String(lang)).label('string1').min(5).max(10);
schema.validate(value);
// Vérification du type string
const value = "billy chaud";
const schema = (new JON.String(lang)).label('string1').label('string1').less(5).greater(10);
schema.validate(value);
// Vérification du type string
const value = "billy";
const schema = (new JON.String(lang)).label('string1').length(5);
schema.validate(value);
// Regex Vérification du type string
const value = "bonjour billy chaud";
const schema = (new JON.String(lang)).label('string1').regexp("^bonjour");
schema.validate(value);
// Regex Vérification du type string - Echec
const value = "bonjour billy chaud";
const schema = (new JON.String(lang)).label('string1').regexp("^Bonjour");
schema.validate(value);
// Alphanumerique Vérification du type string
const value = "bonjour billy";
const schema = (new JON.String(lang)).label('string1').alphanum();
schema.validate(value);
// Alphanumerique Vérification du type string - echec
const value = "bonjour billy chaud@";
const schema = (new JON.String(lang)).label('string1').alphanum();
schema.validate(value);
// Minuscule || Vérification du type string
const value = "bonjour Moniseur BILONG Célestin, comment allez-vous?";
const schema = (new JON.String(lang)).label('string1').lowercase();
schema.validate(value);
// Majuscule || Vérification du type string
const value = "bonjour Moniseur BILONG Célestin, comment allez-vous?";
const schema = (new JON.String(lang)).label('string1').uppercase();
schema.validate(value);
// La première lettre de chaque mot en majuscule || Vérification du type string
const value = "bonjour Moniseur BILONG Célestin, comment allez-vous?";
const schema = (new JON.String(lang)).label('string1').capitalize();
schema.validate(value);
// La première lettre de la phrase en majuscule || Vérification du type string
const value = "bonjour Moniseur BILONG Célestin, comment allez-vous?";
const schema = (new JON.String(lang)).label('string1').ucFirst();
schema.validate(value);
// Verification de carte de credit
const value = '378282246310005';
const schema = (new JON.String(lang)).label('string1').creditCard();
schema.validate(value);
// Verification de carte de credit - Echec
const value = 'lorpem ipsum';
const schema = (new JON.String(lang)).label('string1').creditCard();
schema.validate(value);
// American Card | Verification de carte de credit
const value = '378734493671000';
const schema = (new JON.String(lang)).label('string1').creditCard(
[ 'american-express' ]
);
schema.validate(value);
// Discover | Verification de carte de credit
const value = '6011000990139424';
const schema = (new JON.String(lang)).label('string1').creditCard(
[ 'discover' ]
);
schema.validate(value);
// Diners Club | Verification de carte de credit
const value = '38520000023237';
const schema = (new JON.String(lang)).label('string1').creditCard(
[ 'diners-club' ]
);
schema.validate(value);
// JCB | Verification de carte de credit
const value = '3530111333300000';
const schema = (new JON.String(lang)).label('string1').creditCard(
[ 'jcb' ]
);
schema.validate(value);
// Visa | Verification de carte de credit
const value = '3530111333300000';
const schema = (new JON.String(lang)).label('string1').creditCard(
[ 'jcb' ]
);
schema.validate(value);
// MasterCard | Verification de carte de credit
const value = '5555555555554444';
const schema = (new JON.String(lang)).label('string1').creditCard(
[ 'master-card' ]
);
schema.validate(value);
// Visa | Verification de carte de credit
const value = '4111111111111111';
const schema = (new JON.String(lang)).label('string1').creditCard(
[ 'visa' ]
);
schema.validate(value);
// UBA Card (Visa && Master-card) | Verification de carte de credit
const value = '4012888888881881';
const schema = (new JON.String(lang)).label('string1').creditCard(
[ 'visa', 'master-card' ]
);
schema.validate(value);
// Data URI | Verification de Data URI
const value = 'data:image/gif;base64,R0lGODdhAQABAPAAAP8AAAAAACwAAAAAAQABAAACAkQBADs';
const schema = (new JON.String(lang)).label('string1').dataUri();
schema.validate(value);
// Data URI | Verification de Data URI - Echec
const value = '4012888888881881';
const schema = (new JON.String(lang)).label('string1').dataUri();
schema.validate(value);
// Domain | Verification de Domain
const value = "example.domain.com";
const schema = (new JON.String(lang)).label('string1').domain();
schema.validate(value);
// Domain | Verification de Domain - Echec
const value = '4012888888881881';
const schema = (new JON.String(lang)).label('string1').domain();
schema.validate(value);
// Url | Verification de Url
const value = "255.255.255.255";
const schema = (new JON.String(lang)).label('string1').url();
schema.validate(value);
// Url | Verification de Url
const value = '4012888888881881';
const schema = (new JON.String(lang)).label('string1').url();
schema.validate(value);
// Nom d'hôte | Verification de Nom d'hôte
const value = "255.255.255.255";
const schema = (new JON.String(lang)).label('string1').hostname();
schema.validate(value);
// Nom d'hôte | Verification de Nom d'hôte
const value = '4012888888881881';
const schema = (new JON.String(lang)).label('string1').hostname();
schema.validate(value);
// Adresse IP | Verification de Adresse IP
const value = '912.456.123.123';
const schema = (new JON.String(lang)).label('string1').IPAddress();
schema.validate(value);
// Adresse IP | Verification de Adresse IP
const value = "lorem ipsum";
const schema = (new JON.String(lang)).label('string1').IPAddress();
schema.validate(value);
// IPV4 | Verification de Adresse IP
const value = "192.168.1.1";
const schema = (new JON.String(lang)).label('string1').IPAddress(['ipv4']);
schema.validate(value);
// IPV6 | Verification de Adresse IP
const value = "21DA:D3:0:2F3B:2AA:FF:FE28:9C5A";
const schema = (new JON.String(lang)).label('string1').IPAddress(['ipv6']);
schema.validate(value);
// Email | Verification de Email
const value = '[email protected]';
const schema = (new JON.String(lang)).label('string1').email();
schema.validate(value);
// Email | Verification de Email
const value = "lorem ipsum";
const schema = (new JON.String(lang)).label('string1').email();
schema.validate(value);
// UUID | Verification de UUID
const value = '0D8B604A-59C7-4F44-A385-2FA6DE4CFA0C';
const schema = (new JON.String(lang)).label('string1').guid();
schema.validate(value);
// UUID | Verification de UUID - Echec
const value = "lorem ipsum";
const schema = (new JON.String(lang)).label('string1').guid();
schema.validate(value);
// UUID V1 | Verification de UUID
const value = '12345678-1234-1678-9234-567812345678';
const schema = (new JON.String(lang)).label('string1').guid(['v1']);
schema.validate(value);
// UUID V2 | Verification de UUID
const value = '12345678-1234-2678-8234-567812345678';
const schema = (new JON.String(lang)).label('string1').guid(['v2']);
schema.validate(value);
// UUID V3 | Verification de UUID
const value = '12345678-1234-3678-8234-567812345678';
const schema = (new JON.String(lang)).label('string1').guid(['v3']);
schema.validate(value);
// UUID V4 | Verification de UUID
const value = '12345678-1234-4678-8234-567812345678';
const schema = (new JON.String(lang)).label('string1').guid(['v4']);
schema.validate(value);
// UUID V5 | Verification de UUID
const value = '12345678-1234-5678-8234-567812345678';
const schema = (new JON.String(lang)).label('string1').guid(['v5']);
schema.validate(value);
// Hexadecimal | Verification de Hexadecimal
const value = '1A2B3C4D5E6F7890';
const schema = (new JON.String(lang)).label('string1').hexa();
schema.validate(value);
// Hexadecimal | Verification de Hexadecimal - Echec
const value = "hello123";
const schema = (new JON.String(lang)).label('string1').hexa();
schema.validate(value);
// Hexadecimal | Verification de Hexadecimal
const value = '1A2B3C4D5E6F7890';
const schema = (new JON.String(lang)).label('string1').hexa();
schema.validate(value);
// Hexadecimal | Verification de Hexadecimal - Echec
const value = "hello123";
const schema = (new JON.String(lang)).label('string1').hexa();
schema.validate(value);
// Binaire | Verification de Binaire
const value = '010100';
const schema = (new JON.String(lang)).label('string1').binary();
schema.validate(value);
// Binaire | Verification de Binaire - Echec
const value = "hello123";
const schema = (new JON.String(lang)).label('string1').binary();
schema.validate(value);
// Date | Verification de Date
const value = '2021/03/30 - 05:01:20';
const schema = (new JON.String(lang)).label('string1').date('%Y/%m/%d - %H:%M:%S');
schema.validate(value);
// Date | Verification de Date - Echec
const value = "hello123";
const schema = (new JON.String(lang)).label('string1').date('%Y/%m/%d - %H:%M:%S');
schema.validate(value);
// Identifiant | Verification de Identifiant
const value = 'celest';
const schema = (new JON.String(lang)).label('string1').identifier();
schema.validate(value);
// Identifiant | Verification de Identifiant - Echec
const value = "hello 123";
const schema = (new JON.String(lang)).label('string1').identifier();
schema.validate(value);
// Erreur par defaut | Verification de Erreur par defaut
const value = 'hello 123';
const schema = (new JON.String(lang)).label('default-error').identifier().defaultError("[CUSTOM] Rassurer vous d'entrer un identifiant");
schema.validate(value);
// Ajouter un ecouteur en cas d'erreur | Verification d'une chaîne de caractère
function mapError(
res,
error,
ruleName = undefined,
label = undefined,
lang = 'fr'
) {
console.log("\n>----------------------");
console.log("[CUSTOM] -- JON - mapError | error:: ", error);
console.log("[CUSTOM] -- JON - mapError | ruleName:: ", ruleName);
console.log("[CUSTOM] -- JON - mapError | label:: ", label);
console.log("[CUSTOM] -- JON - mapError | lang:: ", lang);
console.log("\n");
console.log("[CUSTOM] -- JON - mapError | error:: ", error);
console.log("[CUSTOM] -- JON - mapError | res:: ", res);
console.log("-------------------------<");
return res;
}
const value = '456 hello 123';
const schema = (new JON.String(lang)).label('error-listener').identifier().initMapError(mapError);
schema.validate(value);
🔢 Number (Nombre)
// Vérification du type number
const value = 17;
const schema = (new JON.Number(lang)).required().default(10).label('entier1');
schema.validate(value);
// Vérification du type number - Echec
const value = false;
const schema = (new JON.Number(lang)).required().default(10).label('entier1');
schema.validate(value);
// Minimum | Vérification du type number
const value = 20;
const schema = (new JON.Number(lang)).min(5).required().label('entier1');
schema.validate(value);
// Minimum | Vérification du type number - Echec
const value = 4;
const schema = (new JON.Number(lang)).min(5).required().label('entier1');
schema.validate(value);
// Maximum | Vérification du type number
const value = 45;
const schema = (new JON.Number(lang)).max(50).required().label('entier1');
schema.validate(value);
// Maximum | Vérification du type number - Echec
const value = 100;
const schema = (new JON.Number(lang)).max(50).required().label('entier1');
schema.validate(value);
// Strictement inferieur | Vérification du type number
const value = 6;
const schema = (new JON.Number(lang)).less(5).required().label('entier1');
schema.validate(value);
// Strictement inferieur | Vérification du type number - Echec
const value = 5;
const schema = (new JON.Number(lang)).less(5).required().label('entier1');
schema.validate(value);
// Strictement superieur | Vérification du type number
const value = 4;
const schema = (new JON.Number(lang)).greater(5).required().label('entier1');
schema.validate(value);
// Strictement superieur | Vérification du type number - Echec
const value = 5;
const schema = (new JON.Number(lang)).greater(5).required().label('entier1');
schema.validate(value);
// Negatif | Vérification du type number
const value = -20;
const schema = (new JON.Number(lang)).negative().required().label('entier1');
schema.validate(value);
// Negatif | Vérification du type number - Echec
const value = 5;
const schema = (new JON.Number(lang)).negative().required().label('entier1');
schema.validate(value);
// Positif | Vérification du type number
const value = 25;
const schema = (new JON.Number(lang)).positive().required().label('entier1');
schema.validate(value);
// Positif | Vérification du type number - Echec
const value = -5;
const schema = (new JON.Number(lang)).positive().required().label('entier1');
schema.validate(value);
// Nombre signé | Vérification du type number
const value = 20;
const schema = (new JON.Number(lang)).signed().required().label('entier1');
schema.validate(value);
// Nombre signé | Vérification du type number - Echec
const value = 0;
const schema = (new JON.Number(lang)).signed().required().label('entier1');
schema.validate(value);
// Entier | Vérification du type number
const value = 25;
const schema = (new JON.Number(lang)).integer().required().label('entier1');
schema.validate(value);
// Entier | Vérification du type number - Echec
const value = 15.6;
const schema = (new JON.Number(lang)).integer().required().label('entier1');
schema.validate(value);
// Decimal | Vérification du type number
const value = 15.6;
const schema = (new JON.Number(lang)).decimal().required().label('entier1');
schema.validate(value);
// Multiple | Vérification du type number
const value = 6;
const schema = (new JON.Number(lang)).multiple(3).label('entier1');
schema.validate(value);
// Multiple | Vérification du type number - Echec
const value = 8;
const schema = (new JON.Number(lang)).multiple(3).label('entier1');
schema.validate(value);
// Port | Vérification du type number
const value = 80;
const schema = (new JON.Number(lang)).TCPPort().label('entier1');
schema.validate(value);
// Port | Vérification du type number - Echec
const value = 74654646;
const schema = (new JON.Number(lang)).TCPPort().label('entier1');
schema.validate(value);✔️ Boolean (Booléen)
// Vérification du type Boolean
const value = true;
const schema = (new JON.Boolean(lang)).required().label('entier1');
schema.validate(value);
// Vérification du type Boolean - Echec
const value = 5656;
const schema = (new JON.Boolean(lang)).required().label('entier1');
schema.validate(value);📅 Date
// Vérification du type Date
const value = '2020/10/19';
const schema = (new JON.Date(lang)).required().label('date1').changeFormat('%Y/%m/%d');
schema.validate(value);
// Vérification du type Date - Echec
const value = true;
const schema = (new JON.Date(lang)).required().label('date1').changeFormat('%Y/%m/%d');
schema.validate(value);
// Inferieur ou égale à | Vérification du type Date
const value = '2020/10/19';
const schema = (new JON.Date(lang)).required().label('date1').changeFormat('%Y/%m/%d').min('2019/09/03');
schema.validate(value);
// Inferieur ou égale à | Vérification du type Date - Echec
const value = '2018/01/01';
const schema = (new JON.Date(lang)).required().label('date1').changeFormat('%Y/%m/%d').min('2019/09/03');
schema.validate(value);
// Supérieur ou égale à | Vérification du type Date
const value = '2022/10/19';
const schema = (new JON.Date(lang)).required().label('date1').changeFormat('%Y/%m/%d').max('2026/08/02');
schema.validate(value);
// Supérieur ou égale à | Vérification du type Date - Echec
const value = '2030/01/01';
const schema = (new JON.Date(lang)).required().label('date1').changeFormat('%Y/%m/%d').max('2026/08/02');
schema.validate(value);
// Inferieur à | Vérification du type Date
const value = '2020/10/19';
const schema = (new JON.Date(lang)).required().label('date1').changeFormat('%Y/%m/%d').less('2019/09/03');
schema.validate(value);
// Inferieur à | Vérification du type Date - Echec
const value = '2018/01/01';
const schema = (new JON.Date(lang)).required().label('date1').changeFormat('%Y/%m/%d').less('2018/01/01');
schema.validate(value);
// Supérieur à | Vérification du type Date
const value = '2022/10/19';
const schema = (new JON.Date(lang)).required().label('date1').changeFormat('%Y/%m/%d').greater('2026/08/02');
schema.validate(value);
// Supérieur à | Vérification du type Date - Echec
const value = '2030/01/01';
const schema = (new JON.Date(lang)).required().label('date1').changeFormat('%Y/%m/%d').greater('2030/01/01');
schema.validate(value);
// Egale à | Vérification du type Date
const value = '2022/10/19';
const schema = (new JON.Date(lang)).required().label('date1').changeFormat('%Y/%m/%d').equalTo('2022/10/19');
schema.validate(value);
// Egale à | Vérification du type Date - Echec
const value = '2030/01/01';
const schema = (new JON.Date(lang)).required().label('date1').changeFormat('%Y/%m/%d').equalTo('2035/01/01');
schema.validate(value);📊 Array (Tableau)
// Vérification du type array
const value = [ 'lorem', 'ipsum', 'dolor' ];
const schema = (new JON.Array(lang)).label('array1');
schema.validate(value);
// Vérification du type array - Echec
const value = 'lorem';
const schema = (new JON.Array(lang)).label('array1');
schema.validate(value);
// Contient un ou plusieurs types predefinis | Vérification du type array
const value = [ true, 42, false, 3.14 ];
const schema = (new JON.Array(lang)).label('array1').types(
new JON.Boolean(lang).required(),
new JON.Number(lang).required(),
);
schema.validate(value);
// Contient un ou plusieurs types predefinis | Vérification du type array - Echec
const value = [ 'tt', 'lorem' ];
const schema = (new JON.Array(lang)).label('array1').types(
new JON.Boolean(lang).required(),
new JON.Number(lang).required(),
);
schema.validate(value);
// Contient au minimum n valeur(s) | Vérification du type array
const value = [
"Doe",
"Smith",
"Johnson"
];
const schema = (new JON.Array(lang)).min(2).label('array1').required();
schema.validate(value);
// Contient au minimum n valeur(s) | Vérification du type array - Echec
const value = [
"Doe"
];
const schema = (new JON.Array(lang)).min(2).label('array1').required();
schema.validate(value);
// Contient au maximum n valeur(s) | Vérification du type array
const value = [
"John",
30,
true,
{
street: "123 Main St",
city: "Anytown",
zip: "12345"
}
];
const schema = (new JON.Array(lang)).max(5).label('array1').required();
schema.validate(value);
// Contient au minimum n valeur(s) | Vérification du type array - Echec
const value = [
"John",
30,
true,
{
street: "123 Main St",
city: "Anytown",
zip: "12345"
},
'extra value',
999
];
const schema = (new JON.Array(lang)).max(5).label('array1').required();
schema.validate(value);
// Contient au minimum n valeur(s) (n non inclus) | Vérification du type array
const value = [
"Doe",
"Smith",
"Johnson"
];
const schema = (new JON.Array(lang)).greater(1).label('array1').required();
schema.validate(value);
// Contient au minimum n valeur(s) (n non inclus) | Vérification du type array - Echec
const value = [
"Doe"
];
const schema = (new JON.Array(lang)).greater(1).label('array1').required();
schema.validate(value);
// Contient au maximum n valeur(s) (n non inclus) | Vérification du type array
const value = [
"John",
30,
true,
{
street: "123 Main St",
city: "Anytown",
zip: "12345"
}
];
const schema = (new JON.Array(lang)).less(5).label('array1').required();
schema.validate(value);
// Contient au maximum n valeur(s) (n non inclus) | Vérification du type array - Echec
const value = [
"John",
30,
true,
{
street: "123 Main St",
city: "Anytown",
zip: "12345"
},
'extra value'
];
const schema = (new JON.Array(lang)).less(5).label('array1').required();
schema.validate(value);
// Contient exactement n valeur(s) (n non inclus) | Vérification du type array
const value = [
"John",
30,
true,
{
street: "123 Main St",
city: "Anytown",
zip: "12345"
},
'extra value'
];
const schema = (new JON.Array(lang)).length(5).label('array1').required();
schema.validate(value);
// Contient exactement n valeur(s) (n non inclus) | Vérification du type array - Echec
const value = [
"John",
30,
true,
{
street: "123 Main St",
city: "Anytown",
zip: "12345"
}
];
const schema = (new JON.Array(lang)).length(5).label('array1').required();
schema.validate(value);🏗️ Object (Objet)
// Vérification du type object
const value = {
key1: 'value1',
key2: 123,
key3: true
};
const schema = (new JON.Object(lang)).label('object1');
schema.validate(value);
// Vérification du type object - Echec
const value = 'lorem';
const schema = (new JON.Object(lang)).label('object1');
schema.validate(value);
// Structure definie | Vérification du type object
const value = {
name: "Doe",
prename: "John",
age: 30,
isMember: true,
address: {
street: "123 Main St",
city: "Anytown",
zip: "12345"
}
};
const schema = (new JON.Object(lang).struct({
name: (new JON.String(lang)).required().min(2).max(250),
prename: (new JON.String(lang)).min(2).max(250),
age: (new JON.Number(lang)).required(),
isMember: (new JON.Boolean(lang)).default(false),
address: new JON.Object(lang).struct({
street: (new JON.String(lang)).min(2).max(150),
city: (new JON.String(lang)).min(2).max(150),
zip: (new JON.String(lang)).min(2).max(150),
}).required(),
})).label('user').required();
schema.validate(value);
// Structure definie | Vérification du type object - Echec
const value = {
prename: "John",
age: 30,
isMember: true,
address: {
street: "123 Main St",
city: "Anytown",
zip: "12345"
}
};
const schema = (new JON.Object(lang).struct({
name: (new JON.String(lang)).required().min(2).max(250),
prename: (new JON.String(lang)).min(2).max(250),
age: (new JON.Number(lang)).required(),
isMember: (new JON.Boolean(lang)).default(false),
address: new JON.Object(lang).struct({
street: (new JON.String(lang)).min(2).max(150),
city: (new JON.String(lang)).min(2).max(150),
zip: (new JON.String(lang)).min(2).max(150),
}).required(),
})).label('user').required();
schema.validate(value);
// Structure stricte definie | Vérification du type object
const value = {
name: "Doe",
prename: "John"
};
const schema = (new JON.Object(lang).primaryStruct({
name: (new JON.String(lang)).required().min(2).max(250),
prename: (new JON.String(lang)).min(2).max(250),
})).label('user').required();
schema.validate(value);
// Structure stricte definie | Vérification du type object - Echec
const value = {
prename: "John",
};
const schema = (new JON.Object(lang).primaryStruct({
name: (new JON.String(lang)).required().min(2).max(250),
prename: (new JON.String(lang)).min(2).max(250),
})).label('user').required();
schema.validate(value);
// Types de valeurs strictes | Vérification du type object
const value = {
name: "Doe",
prename: "John",
age: 20,
isMember: true,
};
const schema = (new JON.Object(lang)).typesValues(
(new JON.Number(lang)).required(),
(new JON.String(lang)).required(),
).label('user').required();
schema.validate(value);
// Types de valeurs strictes | Vérification du type object - Echec
const value = {
age: 20,
};
const schema = (new JON.Object(lang)).typesValues(
(new JON.Boolean(lang)).required(),
).label('user').required();
schema.validate(value);
// Contient des clés spécifiques | Vérification du type object
const value = {
name: "Doe",
prename: "John",
age: 20,
isMember: true,
};
const schema = (new JON.Object(lang)).containsKeys(
['name', 'prename', 'age', 'isMember',],
).label('user').required();
schema.validate(value);
// Contient des clés spécifiques | Vérification du type object - Echec
const value = {
age: 20,
};
const schema = (new JON.Object(lang)).containsKeys(
['name', 'prename',],
).label('user').required();
schema.validate(value);
// Ne contient pas des clés spécifiques | Vérification du type object
const value = {
age: 20,
};
const schema = (new JON.Object(lang)).noContainsKeys(
['name', 'prename',],
).label('user').required();
schema.validate(value);
// Ne contient pas des clés spécifiques | Vérification du type object - Echec
const value = {
name: "Doe",
prename: "John",
age: 20,
isMember: true,
};
const schema = (new JON.Object(lang)).noContainsKeys(
['name', 'prename', 'age', 'isMember',],
).label('user').required();
schema.validate(value);
// [REGEX] Contient des clés spécifiques | Vérification du type object
const value = {
name: "Doe",
prename: "John",
age: 20,
isMember: true,
};
const schema = (new JON.Object(lang)).regExpContainsKeys(
/^(name|prename|age|isMember)$/,
).label('user').required();
schema.validate(value);
// [REGEX] Contient des clés spécifiques | Vérification du type object - Echec
const value = {
age: 20,
};
const schema = (new JON.Object(lang)).regExpContainsKeys(
/^(name|prename)$/,
).label('user').required();
schema.validate(value);
// [REGEX] Ne contient pas des clés spécifiques | Vérification du type object
const value = {
age: 20,
};
const schema = (new JON.Object(lang)).regExpNoContainsKeys(
/^(name|prename)$/,
).label('user').required();
schema.validate(value);
// [REGEX] Ne contient pas des clés spécifiques | Vérification du type object - Echec
const value = {
name: "Doe",
prename: "John",
age: 20,
isMember: true,
};
const schema = (new JON.Object(lang)).regExpNoContainsKeys(
/^(name|prename|age|isMember)$/,
).label('user').required();
schema.validate(value);
// Contient au minimum n attribut(s) | Vérification du type object
const value = {
name: "Doe",
prename: "John",
};
const schema = (new JON.Object(lang)).min(2).label('user').required();
schema.validate(value);
// Contient au minimum n attribut(s) | Vérification du type object - Echec
const value = {
name: "Doe",
};
const schema = (new JON.Object(lang)).min(2).label('user').required();
schema.validate(value);
// Contient au maximum n attribut(s) | Vérification du type object
const value = {
prename: "John",
age: 30,
isMember: true,
address: {
street: "123 Main St",
city: "Anytown",
zip: "12345"
}
};
const schema = (new JON.Object(lang)).max(5).label('user').required();
schema.validate(value);
// Contient au minimum n attribut(s) | Vérification du type object - Echec
const value = {
prename: "John",
age: 30,
isMember: true,
address: {
street: "123 Main St",
city: "Anytown",
zip: "12345"
}
};
const schema = (new JON.Object(lang)).max(5).label('user').required();
schema.validate(value);
// Contient au minimum n attribut(s) (n non inclus) | Vérification du type object
const value = {
name: "Doe",
prename: "John",
};
const schema = (new JON.Object(lang)).greater(1).label('user').required();
schema.validate(value);
// Contient au minimum n attribut(s) (n non inclus) | Vérification du type object - Echec
const value = {
name: "Doe",
};
const schema = (new JON.Object(lang)).greater(1).label('user').required();
schema.validate(value);
// Contient au maximum n attribut(s) (n non inclus) | Vérification du type object
const value = {
prename: "John",
age: 30,
isMember: true,
address: {
street: "123 Main St",
city: "Anytown",
zip: "12345"
}
};
const schema = (new JON.Object(lang)).less(5).label('user').required();
schema.validate(value);
// Contient au maximum n attribut(s) (n non inclus) | Vérification du type object - Echec
const value = {
prename: "John",
age: 30,
isMember: true,
address: {
street: "123 Main St",
city: "Anytown",
zip: "12345"
},
sex: 'M'
};
const schema = (new JON.Object(lang)).less(5).label('user').required();
schema.validate(value);
// Contient exactement n attribut(s) (n non inclus) | Vérification du type object
const value = {
prename: "John",
age: 30,
isMember: true,
address: {
street: "123 Main St",
city: "Anytown",
zip: "12345"
},
sex: 'M',
};
const schema = (new JON.Object(lang)).length(5).label('user').required();
schema.validate(value);
// Contient exactement n attribut(s) (n non inclus) | Vérification du type object - Echec
const value = {
prename: "John",
age: 30,
isMember: true,
address: {
street: "123 Main St",
city: "Anytown",
zip: "12345"
},
};
const schema = (new JON.Object(lang)).length(5).label('user').required();
schema.validate(value);📁 File (Fichier)
// Vérification du type File (Base64)
const value = 'data:application/javascript;base64,KGFsZXJ0KCdoZWxsbycpKTs=';
const schema = (new JON.File(lang)).required().label('file1');
schema.validate(value);
// Vérification du type File - Echec
const value = 5656;
const schema = (new JON.File(lang)).required().label('file1');
schema.validate(value);
// Vérification du type File
const value = 'data:application/javascript;base64,KGFsZXJ0KCdoZWxsbycpKTs=';
const schema = (new JON.File(lang)).label('file1').min(5).max(17);
schema.validate(value);
// Vérification du type File
const value = 'data:application/javascript;base64,KGFsZXJ0KCdoZWxsbycpKTs=';
const schema = (new JON.File(lang)).label('file1').label('file1').less(5).greater(20);
schema.validate(value);
// Vérification du type File
const value = 'data:application/javascript;base64,KGFsZXJ0KCdoZWxsbycpKTs=';
const schema = (new JON.File(lang)).label('file1').length(17);
schema.validate(value);🎯 Enum (Énumération)
// Vérification du type Enum
const value = 'orange';
const schema = (new JON.Enum(lang)).required().label('enum1').choices('banane', 'orange', 'pomme', 'mangue');
schema.validate(value);
// Vérification du type Enum - Echec
const value = 'macabo';
const schema = (new JON.Enum(lang)).required().label('enum1').choices('banane', 'orange', 'pomme');
schema.validate(value);🚫 NotEnum (Exclusion)
// Vérification du type NotEnum
const value = 'macabo';
const schema = (new JON.NotEnum(lang)).required().label('enum1').choices('banane', 'orange', 'pomme');
schema.validate(value);
// Vérification du type NotEnum - Echec
const value = 'orange';
const schema = (new JON.NotEnum(lang)).required().label('enum1').choices('banane', 'orange', 'pomme', 'mangue');
schema.validate(value);🔄 ChosenType (Choix de type)
// Vérification du type chosenType
const value = 123;
const schema = (new JON.ChosenType(lang)).label('chosen-type-1').choices(
new JON.Boolean(lang).required(),
new JON.Number(lang).required(),
);
schema.validate(value);
// Vérification du type chosenType - Echec
const value = 'lorem';
const schema = (new JON.ChosenType(lang)).label('chosen-type-1').choices(
new JON.Boolean(lang).required(),
new JON.Number(lang).required(),
);
schema.validate(value);✨ AnyType (Type personnalisé)
// classes
class OperationFlexible {
nombres = [];
constructor(...nombres) {
this.nombres = nombres;
}
setNombres(...nombres) {
this.nombres = nombres;
}
getNombres() {
return (
(
typeof this.nombres === 'object' &&
Array.isArray(this.nombres)
) ? this.nombres : []
);
}
addition() {
return this.nombres.reduce((acc, val) => acc + val, 0);
}
soustraction(a) {
return this.nombres.reduce((acc, val) => acc - val, a);
}
multiplication() {
return this.nombres.reduce((acc, val) => acc * val, 1);
}
division(a, b = 1) {
if (b === 0) {
throw new Error("Division par zéro impossible");
}
return a / b;
}
puissance(base, exposant = 1) {
return Math.pow(base, exposant);
}
}
class OperationSecurisee {
constructor() {
this.operations = {
'+': (a, b) => a + b,
'-': (a, b) => a - b,
'*': (a, b) => a * b,
'/': (a, b) => {
if (b === 0) throw new Error("Division par zéro");
return a / b;
},
'%': (a, b) => a % b
};
}
executer(operateur, a, b = this.getValeurParDefaut(operateur)) {
this.validerParametres(operateur, a, b);
const operation = this.operations[operateur];
if (!operation) {
throw new Error(`Opérateur '${operateur}' non supporté`);
}
return operation(a, b);
}
getValeurParDefaut(operateur) {
const defauts = {
'+': 0,
'-': 0,
'*': 1,
'/': 1,
'%': 1
};
return defauts[operateur] || 0;
}
validerParametres(operateur, a, b) {
if (typeof a !== 'number' || typeof b !== 'number') {
throw new Error("Les paramètres doivent être des nombres");
}
if (operateur === '/' && b === 0) {
throw new Error("Division par zéro impossible");
}
}
}
// Definir une contrainte spécifique | Vérification du type anyType
const value = new OperationFlexible(10, 5, 2);
const schema = (new JON.AnyType(lang)).label('any-type-1').applyApp(
(data) => data instanceof OperationFlexible,
(data) => data,
((label) => ({
'fr': `L'attribut "${label}" n'est pas de type "OperationFlexible"`,
'en': `The "${label}" attribute is not of type "OperationFlexible"`,
})),
);
schema.validate(value);
// Definir une contrainte spécifique | Vérification du type anyType - Echec
const value = new OperationSecurisee();
const schema = (new JON.AnyType(lang)).label('any-type-1').applyApp(
(data) => data instanceof OperationFlexible,
(data) => data,
((label) => ({
'fr': `L'attribut "${label}" n'est pas de type "OperationFlexible"`,
'en': `The "${label}" attribute is not of type "OperationFlexible"`,
})),
);
schema.validate(value);
// Mapper l'erreur avant l'affichage | Vérification du type anyType - Echec
function defaultMapError(
res,
error,
ruleName = undefined,
label = undefined,
lang = 'fr'
) {
console.log("\n>----------------------");
console.log("[CUSTOM] -- JON - defaultMapError | error:: ", error);
console.log("[CUSTOM] -- JON - defaultMapError | ruleName:: ", ruleName);
console.log("[CUSTOM] -- JON - defaultMapError | label:: ", label);
console.log("[CUSTOM] -- JON - defaultMapError | lang:: ", lang);
console.log("\n");
console.log("[CUSTOM] -- JON - defaultMapError | error:: ", error);
console.log("[CUSTOM] -- JON - defaultMapError | res:: ", res);
console.log("-------------------------<");
return res;
}
const value = new OperationSecurisee();
const schema = (new JON.AnyType(lang)).label('any-type-1').applyApp(
(data) => data instanceof OperationFlexible,
(data) => data,
((label) => ({
'fr': `L'attribut "${label}" n'est pas de type "OperationFlexible"`,
'en': `The "${label}" attribute is not of type "OperationFlexible"`,
})),
).initMapError(defaultMapError);
schema.validate(value);
// Appliquer un mapping après succès de validation | Vérification du type anyType
const value = new OperationFlexible(10, 5, 2);
const schema = (new JON.AnyType(lang)).label('any-type-1').applyApp(
(data) => data instanceof OperationFlexible,
(data) => data,
((label) => ({
'fr': `L'attribut "${label}" n'est pas de type "OperationFlexible"`,
'en': `The "${label}" attribute is not of type "OperationFlexible"`,
})),
).applyMapping((value) => value.multiplication());
schema.validate(value);
// Appliquer un mapping avant validation | Vérification du type anyType
const value = new OperationFlexible(10, 5, 2);
const schema = (new JON.AnyType(lang)).label('any-type-1').applyApp(
(data) => data instanceof OperationFlexible,
(data) => data,
((label) => ({
'fr': `L'attribut "${label}" n'est pas de type "OperationFlexible"`,
'en': `The "${label}" attribute is not of type "OperationFlexible"`,
})),
).applyPreMapping((value) => {
value.setNombres(...value.getNombres().map(n => n * 2));
return value;
}).applyMapping((value) => value.addition());
schema.validate(value);📄 Licence
MIT License - Voir le fichier LICENSE pour plus de détails.
🐛 Signaler un Bug
Envoyez nous un mail à l'adresse [email protected] pour :
- Signaler un bug
- Proposer une amélioration
- Poser une question
@jsarc/jon - Puissant validateur de données
Développé par l'équipe INICODE
