-
-
Notifications
You must be signed in to change notification settings - Fork 328
/
autoform-validation.js
79 lines (67 loc) · 2.13 KB
/
autoform-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
/* global AutoForm */
import { Meteor } from 'meteor/meteor'
import { throttle } from './common'
import { Utility } from './utility'
/**
* Validates a field on a given form by id.
* @param key {String} a specific schema key to validate
* @param formId {String} the id the form the key belongs to
* @param skipEmpty {Boolean} allows to skip validation if the key has no value
* @param {Boolean} onlyIfAlreadyInvalid
* @return {*}
* @private
*/
const _validateField = function _validateField (
key,
formId,
skipEmpty,
onlyIfAlreadyInvalid
) {
// Due to throttling, this can be called after the autoForm template is destroyed.
// If that happens, we exit without error.
const template = AutoForm.templateInstanceForForm(formId)
// If form is not currently rendered, return true
if (!Utility.checkTemplate(template)) return true
const form = AutoForm.getCurrentDataForForm(formId)
const ss = AutoForm.getFormSchema(formId, form)
if (!ss) return true
// Skip validation if onlyIfAlreadyInvalid is true and the form is
// currently valid.
if (onlyIfAlreadyInvalid && ss.namedContext(formId).isValid()) {
return true // skip validation
}
// Create a document based on all the values of all the inputs on the form
// Get the form type definition
const ftd = Utility.getFormTypeDef(form.type)
// Clean and validate doc
const docToValidate = AutoForm.getFormValues(
formId,
template,
ss,
!!ftd.usesModifier
)
// If form is not currently rendered, return true
if (!docToValidate) {
return true
}
// Skip validation if skipEmpty is true and the field we're validating
// has no value.
if (skipEmpty && !AutoForm.Utility.objAffectsKey(docToValidate, key)) {
return true // skip validation
}
return AutoForm._validateFormDoc(
docToValidate,
!!ftd.usesModifier,
formId,
ss,
form,
key
)
}
// Throttle field validation to occur at most every 300ms,
// with leading and trailing calls.
export const validateField = throttle(_validateField, 300)
// make the original function available to tests
if (Meteor.isPackageTest) {
module.exports = { _validateField }
}