-
Notifications
You must be signed in to change notification settings - Fork 39
/
Copy pathvalidation.js
376 lines (331 loc) · 12.2 KB
/
validation.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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
import _ from 'lodash/fp';
import { Validator } from 'jsonschema';
import { isActivePage, parseISODate } from './helpers';
import {
isValidSSN,
isValidPartialDate,
isValidCurrentOrPastDate,
isValidCurrentOrPastYear,
isValidCurrentOrFutureMonthYear,
isValidDateRange,
isValidPartialMonthYear,
isValidPartialMonthYearInPast
} from './utilities/validations';
/*
* This contains the code for supporting our own custom validations and messages
*/
/*
* Override the default messages for these json schema error types
*/
const defaultMessages = {
required: 'Please provide a response',
'enum': 'Please select a valid option',
maxLength: (max) => `This field should be less than ${max} characters`,
minLength: (min) => `This field should be at least ${min} character(s)`,
format: (type) => {
if (type === 'email') {
return 'Please enter a valid email address';
}
return 'Please enter a valid value';
}
};
function getMessage(path, name, uiSchema, errorArgument) {
let pathSpecificMessage;
if (path === 'instance') {
pathSpecificMessage = _.get(['ui:errorMessages', name], uiSchema);
} else {
const cleanPath = path.replace('instance.', '').replace(/\[\d+\]/g, '.items');
pathSpecificMessage = _.get(`${cleanPath}['ui:errorMessages'].${name}`, uiSchema);
}
if (pathSpecificMessage) {
return pathSpecificMessage;
}
return typeof defaultMessages[name] === 'function'
? defaultMessages[name](errorArgument)
: defaultMessages[name];
}
/*
* This takes the list of errors outputted by the json schema node library
* and moves the required errors to the missing field, rather than the containing
* object.
*
* It also replaces the error messages with any form specific messages.
*/
export function transformErrors(errors, uiSchema) {
const newErrors = errors.map(error => {
if (error.name === 'required') {
const path = `${error.property}.${error.argument}`;
return _.assign(error, {
property: path,
message: getMessage(path, error.name, uiSchema, error.argument)
});
}
const newMessage = getMessage(error.property, error.name, uiSchema, error.argument);
if (newMessage) {
return _.set('message', newMessage, error);
}
return error;
});
return newErrors;
}
/**
* This pulls custom validations specified in the uiSchema and validates the formData
* against them.
*
* Expects validations that look like:
*
* someField: {
* "ui:validations": [
* someValidation
* ]
* }
*
* Each item in the ui:validations array can be a function OR an object:
* - Functions are called with (in order)
* pathErrors: Errors object for the field
* currentData: Data for the field
* formData: Current form data
* schema: Current JSON Schema for the field
* uiSchema['ui:errorMessages']: Error messsage object (if available) for the field
* currentIndex: Used to select the correct field data to validate against
* - Objects should have two properties, 'options' and 'validator'
* options: Object (or anything, really) that will be passed to your validation function.
* You can use this to allow your validation function to be configurable for
* different fields on the form.
* validator: Same signature as function above, but with extra 'options' object as the
* second-to-last argument (...options, currentIndex)
* Both versions of custom validators should call `addError()` to actually add any errors to the
* errors object
*
* @param {Object} errors Errors object from rjsf, which includes an addError method
* @param {Object} uiSchema The uiSchema for the current field
* @param {Object} schema The schema for the current field
* @param {Object} formData The (flattened) data for the entire form
* @param {string} [path] The path to the current field relative to the root of the page.
* @param {number} [currentIndex] Used to select the correct field data to validate against
*/
export function uiSchemaValidate(errors, uiSchema, schema, formData, path = '', currentIndex = null, fullFormData = formData) {
if (uiSchema && schema) {
const currentData = path !== '' ? _.get(path, formData) : formData;
if (uiSchema.items && currentData) {
currentData.forEach((item, index) => {
const newPath = `${path}[${index}]`;
const currentSchema = index < schema.items.length
? schema.items[index]
: schema.additionalItems;
if (!_.get(newPath, errors)) {
const currentErrors = path ? _.get(path, errors) : errors;
currentErrors[index] = {
__errors: [],
addError(error) {
this.__errors.push(error);
}
};
}
uiSchemaValidate(errors, uiSchema.items, currentSchema, formData, newPath, index, fullFormData);
});
} else if (!uiSchema.items) {
Object.keys(uiSchema)
.filter(prop => !prop.startsWith('ui:'))
.forEach((item) => {
const nextPath = path !== '' ? `${path}.${item}` : item;
if (!_.get(nextPath, errors)) {
const currentErrors = path === ''
? errors
: _.get(path, errors);
currentErrors[item] = {
__errors: [],
addError(error) {
this.__errors.push(error);
}
};
}
uiSchemaValidate(errors, uiSchema[item], schema.properties[item], formData, nextPath, currentIndex, fullFormData);
});
}
const validations = uiSchema['ui:validations'];
if (validations && currentData) {
validations.forEach(validation => {
const pathErrors = path ? _.get(path, errors) : errors;
if (typeof validation === 'function') {
validation(pathErrors, currentData, formData, schema, uiSchema['ui:errorMessages'], currentIndex, fullFormData);
} else {
validation.validator(pathErrors, currentData, formData, schema, uiSchema['ui:errorMessages'], validation.options, currentIndex, fullFormData);
}
});
}
}
return errors;
}
export function errorSchemaIsValid(errorSchema) {
if (errorSchema && errorSchema.__errors && errorSchema.__errors.length) {
return false;
}
return _.values(_.omit('__errors', errorSchema)).every(errorSchemaIsValid);
}
export function isValidForm(form, pageListByChapters) {
const pageConfigs = _.flatten(_.values(pageListByChapters));
const validPages = Object.keys(form.pages)
.filter(pageKey => isActivePage(_.find({ pageKey }, pageConfigs), form.data));
const v = new Validator();
const fullFormData = form.data;
return validPages.reduce(({ isValid, errors }, page) => {
const { uiSchema, schema, showPagePerItem, itemFilter, arrayPath } = form.pages[page];
let formData = fullFormData;
if (showPagePerItem) {
const arrayData = formData[arrayPath];
if (arrayData) {
formData = _.set(arrayPath, itemFilter ? arrayData.filter(itemFilter) : arrayData, formData);
} else {
formData = _.unset(arrayPath, formData);
}
}
const result = v.validate(
formData,
schema
);
if (result.valid) {
const customErrors = {};
// Let path and index be their defaults
uiSchemaValidate(customErrors, uiSchema, schema, formData, undefined, undefined, fullFormData);
return {
isValid: isValid && errorSchemaIsValid(customErrors),
errors: errors.concat(customErrors)
};
}
return {
isValid: false,
// removes PII
errors: errors.concat(result.errors.map(_.unset('instance')))
};
}, { isValid: true, errors: [] });
}
export function validateSSN(errors, ssn) {
if (ssn && !isValidSSN(ssn)) {
errors.addError('Please enter a valid 9 digit SSN (dashes allowed)');
}
}
export function validateDate(errors, dateString) {
const { day, month, year } = parseISODate(dateString);
if (!isValidPartialDate(day, month, year)) {
errors.addError('Please provide a valid date');
}
}
export function validateMonthYear(errors, dateString) {
const { month, year } = parseISODate(dateString);
if (!isValidPartialMonthYear(month, year)) {
errors.addError('Please provide a valid date');
}
}
/**
* Adds an error message to errors if a date is an invalid date or in the future.
*
* The message it adds can be customized in uiSchema.errorMessages.futureDate
*/
export function validateCurrentOrPastDate(errors, dateString, formData, schema, errorMessages = {}) {
const { futureDate = 'Please provide a valid current or past date' } = errorMessages;
validateDate(errors, dateString);
const { day, month, year } = parseISODate(dateString);
if (!isValidCurrentOrPastDate(day, month, year)) {
errors.addError(futureDate);
}
}
export function validateCurrentOrPastMonthYear(errors, dateString, formData, schema, errorMessages = {}) {
const { futureDate = 'Please provide a valid current or past date' } = errorMessages;
validateMonthYear(errors, dateString);
const { month, year } = parseISODate(dateString);
if (!isValidPartialMonthYearInPast(month, year)) {
errors.addError(futureDate);
}
}
/**
* Adds an error message to errors if a date is an invalid date or in the past.
*/
export function validateFutureDateIfExpectedGrad(errors, dateString, formData) {
validateDate(errors, dateString);
const { month, year } = parseISODate(dateString);
if (formData.highSchool.status === 'graduationExpected' && !isValidCurrentOrFutureMonthYear(month, year)) {
errors.addError('Please provide a valid future date');
}
}
/**
* Adds an error message to errors if an integer year value is not between 1900 and the current year.
*/
export function validateCurrentOrPastYear(errors, year) {
if (!isValidCurrentOrPastYear(year)) {
errors.addError('Please provide a valid year');
}
}
export function validateMatch(field1, field2, message = 'Please ensure your entries match') {
return (errors, formData) => {
if (formData[field1] !== formData[field2]) {
errors[field2].addError(message);
}
};
}
export function convertToDateField(dateStr) {
const date = parseISODate(dateStr);
return Object.keys(date).reduce((dateField, part) => {
const datePart = {};
datePart[part] = {
value: date[part]
};
return _.assign(dateField, datePart);
}, date);
}
export function validateDateRange(errors, dateRange, formData, schema, errorMessages) {
const fromDate = convertToDateField(dateRange.from);
const toDate = convertToDateField(dateRange.to);
if (!isValidDateRange(fromDate, toDate)) {
errors.to.addError(errorMessages.pattern || 'To date must be on or after from date');
}
}
export function getFileError(file) {
if (file.errorMessage) {
return file.errorMessage;
} else if (file.uploading) {
return 'Uploading file...';
} else if (!file.confirmationCode) {
return 'Something went wrong...';
}
return null;
}
export function validateFileField(errors, fileList) {
fileList.forEach((file, index) => {
const error = getFileError(file);
if (error && !errors[index]) {
/* eslint-disable no-param-reassign */
errors[index] = {
__errors: [],
addError(msg) {
this.__errors.push(msg);
}
};
/* eslint-enable no-param-reassign */
}
if (error) {
errors[index].addError(error);
}
});
}
export function validateBooleanGroup(errors, userGroup, form, schema, errorMessages = {}) {
const { atLeastOne = 'Please choose at least one option' } = errorMessages;
const group = userGroup || {};
if (!Object.keys(group).filter(item => group[item] === true).length) {
errors.addError(atLeastOne);
}
}
export function validateAutosuggestOption(errors, formData) {
if (formData &&
formData.widget === 'autosuggest' &&
!formData.id &&
formData.label) {
errors.addError('Please select an option from the suggestions');
}
}
export function validateCurrency(errors, currencyAmount) {
// Source: https://stackoverflow.com/a/16242575
if (!/(?=.*?\d)^\$?(([1-9]\d{0,2}(,\d{3})*)|\d+)?(\.\d{1,2})?$/.test(currencyAmount)) {
errors.addError('Please enter a valid dollar amount');
}
}