Add some default validators for numbers and string

Signed-off-by: Alexandre Bodin <bodin.alex@gmail.com>
This commit is contained in:
Alexandre Bodin 2020-02-17 12:04:17 +01:00
parent edae06b898
commit c7594f5743
3 changed files with 67 additions and 4 deletions

View File

@ -28,8 +28,17 @@
"component": "default.closingperiod",
"type": "component"
},
"contact_email": {
"type": "email"
},
"stars": {
"required": true,
"type": "integer",
"min": 0,
"max": 3
},
"address": {
"required": true,
"model": "address"
},
"cover": {
@ -55,7 +64,8 @@
},
"description": {
"type": "richtext",
"required": true
"required": true,
"minLength": 10
},
"services": {
"component": "default.restaurantservice",

View File

@ -3,9 +3,11 @@
const yup = require('yup');
const _ = require('lodash');
yup.addMethod(yup.mixed, 'defined', function(msg = '${path} must be defined') {
function isDefined(msg = '${path} must be defined') {
return this.test('defined', msg, value => !_.isNil(value));
});
}
yup.addMethod(yup.mixed, 'defined', isDefined);
/**
* Returns a formatted error for http responses

View File

@ -28,6 +28,57 @@ const stringValidator = composeValidators(
addMaxLengthValidator
);
const enumerationValidator = attr => {
return yup
.string()
.nullable()
.oneOf(Array.isArray(attr.enum) ? attr.enum : [attr.enum]);
};
const emailValidator = composeValidators(stringValidator, (attr, validator) =>
validator.email()
);
const minIntegerValidator = ({ min }, validator) =>
_.isNumber(min) ? validator.min(_.toInteger(min)) : validator;
const maxIntegerValidator = ({ max }, validator) =>
_.isNumber(max) ? validator.max(_.toInteger(max)) : validator;
const integerValidator = composeValidators(
() => yup.number().integer(),
minIntegerValidator,
maxIntegerValidator
);
const minFloatValidator = ({ min }, validator) =>
_.isNumber(min) ? validator.min(min) : validator;
const maxFloatValidator = ({ max }, validator) =>
_.isNumber(max) ? validator.max(max) : validator;
const floatValidator = composeValidators(
() => yup.number(),
minFloatValidator,
maxFloatValidator
);
module.exports = {
string: stringValidator,
text: stringValidator,
richtext: stringValidator,
password: stringValidator,
email: emailValidator,
enumeration: enumerationValidator,
boolean: () => yup.boolean(),
uid: () => yup.mixed(),
json: () => yup.mixed(),
integer: integerValidator,
biginteger: () => yup.mixed(),
float: floatValidator,
decimal: floatValidator,
date: () => yup.mixed(),
time: () => yup.mixed(),
datetime: () => yup.mixed(),
timestamp: () => yup.mixed(),
};