-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
60 lines (46 loc) · 1.4 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
import Ajv from "ajv";
import { JSONSchemaBridge } from "uniforms-bridge-json-schema";
import ajvlocale from "./src/ajvlocale.js";
import registerAjvKeywords from "./src/registerAjvKeywords.js";
import ajv_keywords from "ajv-keywords";
export const ajv = new Ajv({
allErrors: true,
useDefaults: true,
coerceTypes: true,
strict: false,
removeAdditional: true,
$data: true,
});
ajv_keywords(ajv, ["transform"]);
ajv.addKeyword("uniforms");
ajv.addKeyword("options");
// email or empty string
ajv.addFormat(
"email",
/(^[a-z\d.!#$%&'*+/=?^_`{|}~-]+@[a-z\d](?:[a-z\d-]{0,61}[a-z\d])?(?:\.[a-z\d](?:[a-z\d-]{0,61}[a-z\d])?)*$)|(^$)/i,
);
registerAjvKeywords(ajv);
const createValidator = (schema, additionalValidator) => {
const validator = ajv.compile(schema);
return model => {
let errors = [];
validator(model);
if (validator.errors && validator.errors.length) {
errors = validator.errors;
}
if (additionalValidator) {
const additionalValidatorClass = new additionalValidator(model);
const error = additionalValidatorClass.validate(model);
if (error) {
errors = errors.concat(error);
}
}
if (errors.length) {
ajvlocale(errors);
return { details: errors };
}
};
};
export function createSchemaBridge(schema, additionalValidator) {
return new JSONSchemaBridge(schema, createValidator(schema, additionalValidator));
}