/
FormValidator.ts
82 lines (69 loc) · 2.22 KB
/
FormValidator.ts
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
import { LatLng } from 'leaflet';
import Validator from 'validatorjs';
import ruleTranslations from './validationRuleTranslations';
export interface IValidationResult {
isValid: boolean;
errorMessage?: string;
}
const LATITUDE_MIN = 59;
const LATITUDE_MAX = 62;
const LONGITUDE_MIN = 23;
const LONGITUDE_MAX = 27;
const validateLatLngs = (latLng: LatLng) => {
return (
latLng.lat >= LATITUDE_MIN &&
latLng.lat <= LATITUDE_MAX &&
latLng.lng >= LONGITUDE_MIN &&
latLng.lng <= LONGITUDE_MAX
);
};
Validator.register(
'latLngValidator',
validateLatLngs,
'Koordinaatti sallittujen rajojen ulkopuolella.'
);
class FormValidator {
public static validate = (value: any, rule: string): IValidationResult => {
const validator = new Validator(
{
value
},
{
value: rule
},
ruleTranslations
);
const isValid = Boolean(validator.passes());
const firstErrorMessage = validator.errors.first('value');
return {
isValid,
errorMessage: typeof firstErrorMessage === 'string' ? firstErrorMessage : ''
};
};
public static validateAllProperties = (validationModel: object, validationEntity: any) => {
const invalidPropertiesMap: object = {};
Object.entries(validationModel).forEach(([property, validatorRule]) => {
const validationResult = FormValidator.validateProperty(
validatorRule,
validationEntity[property]
);
if (validationResult) {
invalidPropertiesMap[property] = validationResult;
}
});
return invalidPropertiesMap;
};
public static validateProperty = (
validatorRule: string,
value: any
): IValidationResult | undefined => {
if (!validatorRule) return;
return FormValidator.validate(value, validatorRule);
};
public static isInvalidPropertiesMapValid = (invalidPropertiesMap: object) => {
return !Object.values(invalidPropertiesMap).some(
validatorResult => !validatorResult.isValid
);
};
}
export default FormValidator;