/
validate.ts
748 lines (654 loc) · 20.5 KB
/
validate.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
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
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
/*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*
* OpenCRVS is also distributed under the terms of the Civil Registration
* & Healthcare Disclaimer located at http://opencrvs.org/license.
*
* Copyright (C) The OpenCRVS Authors. OpenCRVS and the OpenCRVS
* graphic logo are (registered/a) trademark(s) of Plan International.
*/
import { MessageDescriptor } from 'react-intl'
import { validationMessages as messages } from '@client/i18n/messages'
import {
IFormFieldValue,
IFormData,
IFormField
} from '@opencrvs/client/src/forms'
import {
REGEXP_BLOCK_ALPHA_NUMERIC_DOT,
REGEXP_DECIMAL_POINT_NUMBER,
INFORMANT_MINIMUM_AGE,
NATIONAL_ID
} from '@client/utils/constants'
import { validate as validateEmail } from 'email-validator'
import XRegExp from 'xregexp'
import { IOfflineData } from '@client/offline/reducer'
import { getListOfLocations } from '@client/forms/utils'
import _, { get } from 'lodash'
import format, { convertAgeToDate } from '@client/utils/date-formatting'
/**
* NOTE! When amending validators in this file, remember to also update country configuration typings to reflect the changes
*/
export interface IValidationResult {
message: MessageDescriptor
props?: { [key: string]: any }
}
export type RangeValidation = (
min: number,
max: number
) => (value: IFormFieldValue) => IValidationResult | undefined
export type MaxLengthValidation = (
customisation: number
) => (value: IFormFieldValue) => IValidationResult | undefined
export type Validation = (
value: IFormFieldValue,
drafts?: IFormData,
offlineCountryConfig?: IOfflineData
) => IValidationResult | undefined
export type ValidationInitializer = (...value: any[]) => Validation
export const isAValidPhoneNumberFormat = (value: string): boolean => {
const pattern = window.config.PHONE_NUMBER_PATTERN
return new RegExp(pattern).test(value)
}
export const isAValidEmailAddressFormat = (value: string): boolean => {
return validateEmail(value)
}
export const isAValidDateFormat = (value: string): boolean => {
const dateFormatRegex = '^\\d{4}-(0?[1-9]|1[012])-(0?[1-9]|[12][0-9]|3[01])$'
const dateRegex = new RegExp(dateFormatRegex)
if (!dateRegex.test(value)) {
return false
}
const pad = (n: number) => {
return (str: string) => {
while (str.length < n) {
str = '0' + str
}
return str
}
}
const valueISOString = value.split(/-/g).map(pad(2)).join('-')
const givenDate = new Date(valueISOString)
return givenDate.toISOString().slice(0, 10) === valueISOString
}
export const requiredBasic: Validation = (value: IFormFieldValue) =>
value ? undefined : { message: messages.requiredBasic }
export const requiredSymbol: Validation = (value: IFormFieldValue) =>
value ? undefined : { message: messages.requiredSymbol }
export const required =
(message: MessageDescriptor = messages.required): Validation =>
(value: IFormFieldValue) => {
if (typeof value === 'string') {
return value !== '' ? undefined : { message }
}
if (Array.isArray(value)) {
return value.length > 0 ? undefined : { message }
}
return value !== undefined && value !== null ? undefined : { message }
}
export const minLength = (min: number) => (value: string) => {
return value && value.length < min
? { message: messages.minLength, props: { min } }
: undefined
}
export const validLength = (length: number) => (value: IFormFieldValue) => {
return value && value.toString().length === length
? undefined
: {
message: messages.validNationalId,
props: { validLength: length }
}
}
const isLessOrEqual = (value: string, max: number) => {
return value && value.toString().length <= max
}
export const maxLength: MaxLengthValidation =
(max: number) => (value: IFormFieldValue) => {
return isLessOrEqual(value as string, max)
? undefined
: { message: messages.maxLength, props: { max } }
}
const isNumber = (value: string): boolean => !value || !isNaN(Number(value))
const isRegexpMatched = (value: string, regexp: string): boolean =>
!value || value.match(regexp) !== null
export const blockAlphaNumericDot: Validation = (value: IFormFieldValue) => {
const cast = value as string
return isRegexpMatched(cast, REGEXP_BLOCK_ALPHA_NUMERIC_DOT)
? undefined
: { message: messages.blockAlphaNumericDot }
}
export const nonDecimalPointNumber: Validation = (value: IFormFieldValue) => {
const cast = value as string
if (cast) {
return !isRegexpMatched(cast.toString(), REGEXP_DECIMAL_POINT_NUMBER)
? undefined
: { message: messages.nonDecimalPointNumber }
}
}
export const numeric: Validation = (value: IFormFieldValue) => {
const cast = value as string
return isNumber(cast) ? undefined : { message: messages.numberRequired }
}
export const facilityMustBeSelected: Validation = (
value: IFormFieldValue,
drafts,
offlineCountryConfig
) => {
const locationsList = getListOfLocations(
offlineCountryConfig as IOfflineData,
'facilities'
)
const isValid = !value || locationsList[value as string]
return isValid ? undefined : { message: messages.facilityMustBeSelected }
}
export const officeMustBeSelected: Validation = (
value: IFormFieldValue,
drafts,
offlineCountryConfig
) => {
const locationsList = getListOfLocations(
offlineCountryConfig as IOfflineData,
'offices'
)
const isValid = !value || locationsList[value as string]
return isValid ? undefined : { message: messages.officeMustBeSelected }
}
export const phoneNumberFormat: Validation = (value: IFormFieldValue) => {
const cast = value as string
const trimmedValue = cast === undefined || cast === null ? '' : cast.trim()
if (!trimmedValue) {
return undefined
}
return isAValidPhoneNumberFormat(trimmedValue)
? undefined
: {
message: messages.phoneNumberFormat
}
}
export const emailAddressFormat: Validation = (value: IFormFieldValue) => {
const cast = value as string
if (cast === '') {
return
}
return cast && isAValidEmailAddressFormat(cast)
? undefined
: {
message: messages.emailAddressFormat
}
}
export const dateFormat: Validation = (value: IFormFieldValue) => {
const cast = value as string
return cast && isAValidDateFormat(cast)
? undefined
: {
message: messages.dateFormat
}
}
export const isDateNotInFuture = (date: string) => {
return new Date(date) <= new Date(Date.now())
}
export const isDateNotBeforeBirth = (date: string, drafts: IFormData) => {
const birthDate = drafts.deceased && drafts.deceased.birthDate
return birthDate
? new Date(date) >= new Date(JSON.stringify(birthDate))
: true
}
export const isDateNotAfterBirthEvent = (date: string, drafts?: IFormData) => {
const dateOfBirth = drafts && drafts.child && drafts.child.childBirthDate
return dateOfBirth
? new Date(date) <= new Date(JSON.stringify(dateOfBirth))
: true
}
export const isDateNotAfterDeath = (date: string, drafts?: IFormData) => {
const deathDate = drafts && drafts.deathEvent && drafts.deathEvent.deathDate
return deathDate
? new Date(date).setHours(0, 0, 0, 0) <=
new Date(JSON.stringify(deathDate)).setHours(0, 0, 0, 0)
: true
}
export const isDateAfter = (first: string, second: string) => {
return new Date(first) >= new Date(second)
}
export const minAgeGapExist = (
first: string,
second: string,
minAgeGap: number
): boolean => {
const diff =
(new Date(first).getTime() - new Date(second).getTime()) /
(1000 * 60 * 60 * 24) /
365
return diff >= minAgeGap
}
export const isValidBirthDate: Validation = (
value: IFormFieldValue,
drafts?
) => {
const cast = value as string
return !cast
? { message: messages.required }
: cast &&
isDateNotInFuture(cast) &&
isAValidDateFormat(cast) &&
isDateNotAfterBirthEvent(cast, drafts as IFormData)
? isDateNotAfterDeath(cast, drafts as IFormData)
? undefined
: {
message: messages.isDateNotAfterDeath
}
: {
message: messages.isValidBirthDate
}
}
export const isValidChildBirthDate: Validation = (value: IFormFieldValue) => {
const childBirthDate = value as string
return !childBirthDate
? { message: messages.required }
: childBirthDate &&
isAValidDateFormat(childBirthDate) &&
isDateNotInFuture(childBirthDate)
? undefined
: { message: messages.isValidBirthDate }
}
export const isValidParentsBirthDate =
(minAgeGap: number, isAge?: boolean): Validation =>
(value: IFormFieldValue, drafts) => {
const parentsBirthDate = isAge
? convertAgeToDate(value as string)
: (value as string)
const childBirthDate =
drafts && drafts.child && (drafts.child.childBirthDate as string)
return parentsBirthDate &&
isAValidDateFormat(parentsBirthDate) &&
isDateNotInFuture(parentsBirthDate)
? childBirthDate
? minAgeGapExist(childBirthDate, parentsBirthDate, minAgeGap)
? undefined
: {
message: messages.isValidBirthDate
}
: undefined
: {
message: messages.isValidBirthDate
}
}
export const checkBirthDate =
(marriageDate: string): Validation =>
(value: IFormFieldValue) => {
const cast = value as string
if (!isAValidDateFormat(cast)) {
return {
message: messages.dateFormat
}
}
const bDate = new Date(cast)
// didn't call `isDateNotInFuture(value)`, because no need to call `new Date(value)` twice
if (bDate > new Date()) {
return {
message: messages.dateFormat
}
}
if (!marriageDate || !isAValidDateFormat(marriageDate)) {
return undefined
}
return bDate < new Date(marriageDate)
? undefined
: {
message: messages.dobEarlierThanDom
}
}
const getBirthDate = (
isExactDateOfBirthUnknown: boolean,
date: string,
age: string
) => (isExactDateOfBirthUnknown ? convertAgeToDate(age) : date)
export const checkMarriageDate =
(minAge: number): Validation =>
(value: IFormFieldValue, drafts) => {
const cast = value as string
if (!isAValidDateFormat(cast)) {
return {
message: messages.dateFormat
}
}
const mDate = new Date(cast)
// didn't call `isDateNotInFuture(value)`, because no need to call `new Date(value)` twice
if (mDate > new Date()) {
return {
message: messages.dateFormat
}
}
const groomDOB =
drafts &&
drafts.groom &&
getBirthDate(
Boolean(drafts.groom.exactDateOfBirthUnknown),
String(drafts.groom.groomBirthDate),
String(drafts.groom.ageOfIndividualInYears)
)
const brideDOB =
drafts &&
drafts.bride &&
getBirthDate(
Boolean(drafts.bride.exactDateOfBirthUnknown),
String(drafts.bride.brideBirthDate),
String(drafts.bride.ageOfIndividualInYears)
)
if (!groomDOB || !brideDOB) {
return undefined
} else {
if (
!minAgeGapExist(cast, groomDOB, minAge) ||
!minAgeGapExist(cast, brideDOB, minAge)
) {
return {
message: messages.illegalMarriageAge
}
} else if (mDate < new Date(groomDOB) && mDate < new Date(brideDOB)) {
return {
message: messages.domLaterThanDob
}
} else {
return undefined
}
}
}
export const isValidDateOfBirthForMarriage =
(sectionName: string, minAge: number): Validation =>
(value: IFormFieldValue, drafts) => {
const isExactDateOfBirthUnknown =
drafts &&
drafts[sectionName] &&
drafts[sectionName].exactDateOfBirthUnknown
const cast = isExactDateOfBirthUnknown
? convertAgeToDate(value as string)
: (value as string)
if (!isAValidDateFormat(cast)) {
return {
message: messages.dateFormat
}
} else if (!isDateNotInFuture(cast)) {
return { message: messages.isValidBirthDate }
}
if (
!minAgeGapExist(
format(new Date(Date.now()), 'yyyy-MM-dd'),
String(value),
minAge
)
) {
return {
message: messages.illegalMarriageAge
}
} else {
return undefined
}
}
export const dateGreaterThan =
(previousDate: string): Validation =>
(value: IFormFieldValue) => {
const cast = value as string
if (!previousDate || !isAValidDateFormat(previousDate)) {
return undefined
}
return new Date(cast) > new Date(previousDate)
? undefined
: {
message: messages.domLaterThanDob
}
}
export const dateLessThan =
(laterDate: string): Validation =>
(value: IFormFieldValue) => {
const cast = value as string
if (!laterDate || !isAValidDateFormat(laterDate)) {
return undefined
}
return new Date(cast) < new Date(laterDate)
? undefined
: {
message: messages.dobEarlierThanDom
}
}
export const dateNotInFuture = (): Validation => (value: IFormFieldValue) => {
const cast = value as string
if (isDateNotInFuture(cast)) {
return undefined
} else {
return { message: messages.dateFormat }
}
}
export const dateNotToday = (date: string): boolean => {
const today = new Date().setHours(0, 0, 0, 0)
const day = new Date(date).setHours(0, 0, 0, 0)
return day !== today
}
export const isDateInPast: Validation = (value: IFormFieldValue) => {
const cast = value as string
if (isDateNotInFuture(cast) && dateNotToday(cast)) {
return undefined
} else {
return { message: messages.isValidBirthDate } // specific to DOB of parent/informant
}
}
export const dateInPast = (): Validation => (value: IFormFieldValue) =>
isDateInPast(value)
export const dateFormatIsCorrect = (): Validation => (value: IFormFieldValue) =>
dateFormat(value as string)
/*
* TODO: The name validation functions should be refactored out.
*
* Name validation has some complexities. These will vary from country to
* country too. e.g. in Bangladesh there is actually no given name or
* family name. Or first name/last name. To fit names in the common western
* format, people have to use multiple words in a "first name" or a "last name".
*
* Another complexity is what letters are allowed. Should we allow hyphens?
* Then in Bengali, there are some rules which we can build to ensure better
* quality input. e.g. a word can not start with a "mark" or diatribe.
*
* For now, we are going with simple validation that just prevents entering
* an English name in the Bengali name field and vice versa.
*/
// Each character has to be a part of the Unicode Bengali script or the hyphen.
export const isValidBengaliWord = (value: string): boolean => {
const bengaliRe = XRegExp.cache(
'(^[\\p{Bengali}.-]*\\([\\p{Bengali}.-]+\\)[\\p{Bengali}.-]*$)|(^[\\p{Bengali}.-]+$)',
''
)
const lettersRe = XRegExp.cache(
'(^[\\pL\\pM.-]*\\([\\pL\\pM.-]+\\)[\\pL\\pM.-]*$)|(^[\\pL\\pM.-]+$)',
''
)
return bengaliRe.test(value) && lettersRe.test(value)
}
//
// Simple pattern. Allow only English (Latin) characters and the hyphen.
//
export const isValidEnglishWord = (value: string): boolean => {
// Still using XRegExp for its caching ability
const englishRe = XRegExp.cache(
`(^[\\p{Latin}0-9'._-]*\\([\\p{Latin}0-9'._-]+\\)[\\p{Latin}0-9'._-]*$)|(^[\\p{Latin}0-9'._-]+$)`,
''
)
return englishRe.test(value)
}
type Checker = (value: string) => boolean
// Utility 2nd order function. Does a little common task then passes on to
// the callback.
const checkNameWords = (value: string, checker: Checker): boolean => {
const trimmedValue = value === undefined || value === null ? '' : value.trim()
if (!trimmedValue) {
return true
}
const parts: string[] = trimmedValue.split(/\s+/)
return parts.every(checker)
}
export const isValidBengaliName = (value: string): boolean => {
return checkNameWords(value, isValidBengaliWord)
}
export const isValidEnglishName = (value: string): boolean => {
return checkNameWords(value, isValidEnglishWord)
}
export const isLengthWithinRange = (value: string, min: number, max: number) =>
!value || (value.length >= min && value.length <= max)
export const isValueWithinRange =
(min: number, max: number) =>
(value: number): boolean => {
return !isNaN(value) && value >= min && value <= max
}
export const bengaliOnlyNameFormat: Validation = (value: IFormFieldValue) => {
const cast = value as string
return isValidBengaliName(cast)
? undefined
: { message: messages.bengaliOnlyNameFormat }
}
export const englishOnlyNameFormat: Validation = (value: IFormFieldValue) => {
const cast = value as string
return isValidEnglishName(cast)
? undefined
: { message: messages.englishOnlyNameFormat }
}
export const range: RangeValidation =
(min: number, max: number) => (value: IFormFieldValue) => {
const cast = value as string
return isValueWithinRange(min, max)(parseFloat(cast))
? undefined
: { message: messages.range, props: { min, max } }
}
export const oneOf = (
fields: string[],
errorMessage: MessageDescriptor
): Validation => {
return (_value, fieldValues) => {
const someFilled = fields.some((field) => get(fieldValues, field))
if (someFilled) {
return undefined
}
return { message: errorMessage }
}
}
export const isAValidNIDNumberFormat = (value: string): boolean => {
const pattern = window.config.NID_NUMBER_PATTERN
return new RegExp(pattern).test(value)
}
export const validIDNumber =
(typeOfID: string): Validation =>
(value: any) => {
value = (value && value.toString()) || ''
const cast = value as string
const trimmedValue = cast === undefined || cast === null ? '' : cast.trim()
if (typeOfID === NATIONAL_ID) {
if (isAValidNIDNumberFormat(trimmedValue) || !trimmedValue) {
return undefined
}
return {
message: messages.validNationalId
}
}
return undefined
}
export const duplicateIDNumber =
(fieldToDuplicateCheck: string): Validation =>
(value: IFormFieldValue, drafts) => {
const valueToCheck = _.get(drafts, fieldToDuplicateCheck)
if (value && valueToCheck && value === valueToCheck) {
return {
message: messages.duplicateNationalID
}
}
return undefined
}
export const isValidDeathOccurrenceDate: Validation = (
value: IFormFieldValue,
drafts
) => {
const cast = value && value.toString()
return cast && isDateNotInFuture(cast) && isAValidDateFormat(cast)
? isDateNotBeforeBirth(cast, drafts as IFormData)
? undefined
: {
message: messages.isDateNotBeforeBirth
}
: {
message: messages.isValidDateOfDeath
}
}
export const isMoVisitDateAfterBirthDateAndBeforeDeathDate: Validation = (
value: IFormFieldValue,
drafts
) => {
const cast = value && value.toString()
if (drafts && drafts.deathEvent && !drafts.deathEvent.birthDate) {
if (drafts && drafts.deathEvent && cast <= drafts.deathEvent.deathDate) {
return undefined
} else if (
drafts &&
drafts.deathEvent &&
cast > drafts.deathEvent.deathDate
) {
return {
message: messages.isMoVisitAfterDeath
}
}
} else {
if (
drafts &&
drafts.deathEvent &&
cast <= drafts.deathEvent.deathDate &&
cast >= drafts.deceased.birthDate
) {
return undefined
} else if (
drafts &&
drafts.deathEvent &&
cast > drafts.deathEvent.deathDate
) {
return {
message: messages.isMoVisitAfterDeath
}
} else if (
drafts &&
drafts.deathEvent &&
cast < drafts.deceased.birthDate
) {
return {
message: messages.isMoVisitBeforeBirth
}
}
}
}
export const isInformantOfLegalAge: Validation = (value: IFormFieldValue) => {
if (value) {
if (
minAgeGapExist(
format(new Date(Date.now()), 'yyyy-MM-dd'),
value.toString(),
INFORMANT_MINIMUM_AGE
)
) {
return undefined
} else {
return {
message: messages.isInformantOfLegalAge
}
}
}
}
export const greaterThanZero: Validation = (value: IFormFieldValue) => {
return !value && value !== 0
? { message: messages.required }
: value && Number(value) > 0
? undefined
: { message: messages.greaterThanZero }
}
export const notGreaterThan =
(maxValue: number): Validation =>
(value: IFormFieldValue) => {
const numericValue = Number.parseInt(value as string)
return value && !Number.isNaN(numericValue) && numericValue <= maxValue
? undefined
: { message: messages.notGreaterThan, props: { maxValue } }
}