forked from PolymerElements/iron-validatable-behavior
-
Notifications
You must be signed in to change notification settings - Fork 0
/
iron-validation-trigger-behavior.html
92 lines (79 loc) · 3.01 KB
/
iron-validation-trigger-behavior.html
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
<link rel="import" href="../polymer/polymer.html">
<script>
/**
* 'Polymer.IronValidationTriggerBehavior` decides when form input will be validated.
* The behavior needs to be applied to iron-input (or other elements implementing bindValue and `ironValidatablebehavior`).
*
* Validation of a form field will be triggered when the user:
* <ol>
* <li>leaves a form field -> This will be applied when input is still 'untouched'</li>
* <li>on keyup (actually, on the input event) -> This will be applied when input already 'touched'</li>
* </ol>
*
* By default, this behavior is disabled when applied. In order to enable, set the 'auto-validate' property ro true
*
* @demo demo/index.html
* @element iron-validation-trigger-behavior
* @polymerBehavior
*/
Polymer.IronValidationTriggerBehavior = {
properties: {
/**
* When true, the behavior will manage 'touched' and 'dirty' states and validate on blur/bind-value-changed
* @private
*/
autoValidate: {
type: Boolean,
value: false
}
},
/**
* Register event handlers and validate prefilled inputs
*/
attached: function () {
if(!this.autoValidate) {
return;
}
this.addEventListener('blur', this._valTrigOnBlur.bind(this));
this.addEventListener('bind-value-changed', this._valTrigOnValueChange.bind(this));
// Since we not only want to validate on 'input' event, but to every (bind-)value change (implemented by iron-input and iron-autogrow-textarea)
if (this.value) {
this.validate();
this._setTouched(true); // treat this as if it were touched, so that validation will be performed on keyup
}
},
/**
* Deregister event handlers
*/
detached: function () {
if(!this.autoValidate) {
return;
}
this.removeEventListener('blur', this._valTrigOnBlur);
this.removeEventListener('bind-value-changed', this._valTrigOnValueChange);
},
/**
* Sets touched value and validates when already dirty.
* Resets the touched state when user leaves a field without a value. On next interaction, user will start with a clean slave
* @private
*/
_valTrigOnBlur: function () {
if (this.dirty) {
this.validate();
}
this._setTouched(!!this.value);
},
/**
* Sets dirty value and validates when already touched or invalid
* @private
*/
_valTrigOnValueChange: function () {
this._setDirty(true);
if (this.touched || this.invalid) {
this.debounce('validate', function () {
this.validate();
}, 100);
}
}
};
</script>