-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathConditionalRequiredAttribute.validation.js
85 lines (76 loc) · 2.98 KB
/
ConditionalRequiredAttribute.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
$.validator.addMethod('conditionalrequired', function (value, element, parameters) {
var andExpressions = JSON.parse(parameters['expression']);
var result = true;
andExpressions.forEach(function (andExpression) {
var _res = false;
andExpression.forEach(function (orExpression) {
var actualValue = _cast(_getElementValue(orExpression.Property), typeof orExpression.Value);
if (_compare(actualValue, orExpression.Value, orExpression.Operator.Text)) {
_res = true;
return;
}
});
if (!_res) {
result = false;
return;
}
});
function _cast(val, type) {
if (!val)
return null;
switch (type) {
case 'number':
return +val;
case 'boolean':
return (val === 'true' || val === 'True');
case 'string':
default:
return val;
}
}
function _getElementValue(name) {
var els = document.getElementsByName(name);
var el1 = els[0];
if (!els.length)
return null;
if (els.length > 1) {
if (el1.tagName.toLowerCase() === 'input' && (el1.type === 'radio' || el1.type === 'checkbox'))
for (var i = 0; i < els.length; i++) {
var el = els[i];
if (el.checked)
return el.value;
}
} else {
if (el1.tagName.toLowerCase() === 'input' && el1.type === 'checkbox')
return (el1.checked ? el1.value : null);
else
return el1.value;
}
return null;
}
function _compare(actualValue, compareValue, operator) {
switch (operator) {
case '==':
return actualValue === compareValue;
case '!=':
return actualValue !== compareValue;
case '>':
return actualValue > compareValue;
case '<':
return actualValue < compareValue;
case '>=':
return actualValue >= compareValue;
case '<=':
return actualValue <= compareValue;
default:
throw 'wrong operator';
}
}
if (result)
return $.validator.methods.required.call(this, value, element, parameters);
return true;
});
$.validator.unobtrusive.adapters.add('conditionalrequired', ['expression'], function(options) {
options.rules['conditionalrequired'] = { expression: options.params['expression'] };
options.messages['conditionalrequired'] = options.message;
});