forked from PolymerElements/gold-phone-input
-
Notifications
You must be signed in to change notification settings - Fork 1
/
gold-phone-input.html
368 lines (290 loc) · 11.1 KB
/
gold-phone-input.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
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
<!--
@license
Copyright (c) 2015 The Polymer Project Authors. All rights reserved.
This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt
Code distributed by Google as part of the polymer project is also
subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt
-->
<link rel="import" href="../polymer/polymer.html">
<link rel="import" href="../paper-input/paper-input-behavior.html">
<link rel="import" href="../paper-input/paper-input-container.html">
<link rel="import" href="../paper-input/paper-input-error.html">
<link rel="import" href="../paper-styles/typography.html">
<link rel="import" href="../iron-input/iron-input.html">
<link rel="import" href="../iron-form-element-behavior/iron-form-element-behavior.html">
<link rel="import" href="../iron-flex-layout/iron-flex-layout.html">
<!--
`<gold-phone-input>` is a single-line text field with Material Design styling
for entering a phone number.
<gold-phone-input></gold-phone-input>
It may include an optional label, which by default is "Phone number".
<gold-phone-input label="call this"></gold-phone-input>
### Validation
By default, the phone number is considered to be a US phone number, and
will be validated according to the pattern `XXX-XXX-XXXX`, where `X` is a
digit, and `-` is the separating dash. Formatting also supports single spaces. If you want to customize the input
for a different area code or number pattern, use the `country-code` and
`phone-number-pattern` attributes.
<gold-phone-input
country-code="33"
phone-number-pattern="X-XX-XX-XX-XX">
</gold-phone-input>
The input can be automatically validated as the user is typing by using
the `auto-validate` and `required` attributes. For manual validation, the
element also has a `validate()` method, which returns the validity of the
input as well sets any appropriate error messages and styles.
See `Polymer.PaperInputBehavior` for more API docs.
### Styling
See `Polymer.PaperInputContainer` for a list of custom properties used to
style this element.
`--gold-phone-input-country-code` | Mixin applied to the country code span
@group Gold Elements
@hero hero.svg
@demo demo/index.html
@class gold-phone-input
-->
<dom-module id="gold-phone-input">
<template>
<style>
:host {
display: block;
}
/* TODO: This should be a dropdown */
span {
@apply(--paper-font-subhead);
@apply(--paper-input-container-input);
width: 40px;
}
.country-code {
@apply(--gold-phone-input-country-code);
}
.label-no-country-code {
left: 0 !important;
}
.container {
@apply(--layout-horizontal);
}
/* TODO(notwaldorf): The style applied by paper-input-container is more
* specific, and we need the important to override it. This will go away
* once we can refactor this element to use the paper-input suffix */
label {
left: 40px !important;
}
input {
@apply(--layout-flex);
}
</style>
<paper-input-container id="container"
disabled$="[[disabled]]"
no-label-float="[[noLabelFloat]]"
always-float-label="[[_computeAlwaysFloatLabel(alwaysFloatLabel,placeholder)]]"
invalid="[[invalid]]">
<label hidden$="[[!label]]">[[label]]</label>
<div class="container">
<span hidden$="[[noCountryCode]]" class="country-code">+[[countryCode]]</span>
<input is="iron-input" id="input"
aria-labelledby$="[[_ariaLabelledBy]]"
aria-describedby$="[[_ariaDescribedBy]]"
required$="[[required]]"
bind-value="{{value}}"
name$="[[name]]"
allowed-pattern="[()\s0-9\-]"
autocomplete="tel"
type="tel"
prevent-invalid-input
disabled$="[[disabled]]"
invalid="{{invalid}}"
autofocus$="[[autofocus]]"
inputmode$="[[inputmode]]"
placeholder$="[[placeholder]]"
readonly$="[[readonly]]"
maxlength$="[[maxlength]]"
size$="[[size]]">
</div>
<template is="dom-if" if="[[errorMessage]]">
<paper-input-error id="error">[[errorMessage]]</paper-input-error>
</template>
</paper-input-container>
</template>
<script>
Polymer({
is: 'gold-phone-input',
behaviors: [
Polymer.PaperInputBehavior,
Polymer.IronFormElementBehavior
],
properties: {
/**
* The label for this input.
*/
label: {
type: String,
value: 'Phone number'
},
/*
* The country code that should be recognized and parsed.
*/
countryCode: {
type: String,
value: '1'
},
/*
* Set this to true to disable the country code
*/
noCountryCode: {
type: Boolean,
value: false
},
/*
* The format of a valid phone number, including formatting but excluding
* the country code. Use 'X' to denote the digits separated by dashes.
*/
phoneNumberPattern: {
type: String,
value: 'XXX-XXX-XXXX',
observer: '_phoneNumberPatternChanged'
},
value: {
type: String,
observer: '_onValueChanged'
}
},
observers: [
'_onFocusedChanged(focused)'
],
ready: function() {
// If there's an initial input, validate it.
if (this.value)
this._handleAutoValidate();
},
attached: function() {
if(this.noCountryCode) {
this.set('countryCode', '');
Polymer.dom(this).node.querySelector('label').classList.add('label-no-country-code');
}
this.set('maxlength', this.phoneNumberPattern.length);
},
_phoneNumberPatternChanged: function() {
// Transform the pattern into a regex the iron-input understands.
var regex = '';
regex = this.phoneNumberPattern.replace(/\s/g, '\\s');
regex = regex.replace(/\(/gi, '\\(');
regex = regex.replace(/\)/gi, '\\)');
regex = regex.replace(/X/gi, '\\d');
regex = regex.replace(/\+/g, '\\+');
this.$.input.pattern = regex;
this.regex = regex;
},
/**
* A handler that is called on input
*/
_onValueChanged: function(value, oldValue) {
// The initial property assignment is handled by `ready`.
if (oldValue == undefined || value == undefined) {
this.value = '';
return;
}
value = value ? value.toString() : '';
// Keep track of how many dashes the original value has. After
// reformatting the value, we might gain or lose some of them, which
// means we have to correctly move the caret to account for the difference.
var start = this.$.input.selectionStart;
var initialDashesBeforeCaret = value.substr(0, start).split('-').length - 1;
var initialSpacesBeforeCaret = value.substr(0, start).split(' ').length - 1;
var initialLeftParenBeforeCaret = value.substr(0, start).split('(').length - 1;
var initialRightParenBeforeCaret = value.substr(0, start).split(')').length - 1;
var formattedValue = '';
// Remove any already-applied formatting.
value = value.replace(/-/g, '');
value = value.replace(/\(/g, '');
value = value.replace(/\)/g, '');
value = value.replace(/\s/g, '');
oldValue = oldValue.replace(/-/g, '');
oldValue = oldValue.replace(/\(/g, '');
oldValue = oldValue.replace(/\)/g, '');
oldValue = oldValue.replace(/\s/g, '');
if(value === oldValue) {
return;
}
if(value.length > 10) {
this.updateValueAndPreserveCaret(value.trim());
this._handleAutoValidate();
return;
}
// Fill in the dashes according to the specified pattern.
var leftParenIndex = this.phoneNumberPattern.indexOf('(');
var leftParenAdded = false;
var rightParenIndex = this.phoneNumberPattern.indexOf(')') - 1;
var rightParenAdded = false;
var currentSpaceIndex = 0;
var currentDashIndex = 0;
var totalCharactersAdded = 0;
for (var i = 0; i < value.length; i++) {
currentDashIndex = this.phoneNumberPattern.indexOf('-', currentDashIndex);
currentSpaceIndex = this.phoneNumberPattern.indexOf(' ', currentSpaceIndex);
// Since we remove any formatting first, we need to account added dashes, etc.
// when counting the position of new dashes in the pattern.
if (i == leftParenIndex) {
formattedValue += '(';
leftParenAdded = true;
totalCharactersAdded++;
}
if (i == rightParenIndex) {
formattedValue += ')';
rightParenAdded = true;
totalCharactersAdded++;
}
if (i == (currentSpaceIndex - totalCharactersAdded)) {
formattedValue += ' ';
currentSpaceIndex++;
totalCharactersAdded++;
}
if (i == (currentDashIndex - totalCharactersAdded)) {
formattedValue += '-';
currentDashIndex++;
totalCharactersAdded++;
}
formattedValue += value[i];
}
var updatedDashesBeforeCaret = formattedValue.substr(0, start).split('-').length - 1;
var dashesDifference = updatedDashesBeforeCaret - initialDashesBeforeCaret;
var updatedSpacesBeforeCaret = formattedValue.substr(0, start+1).split(' ').length - 1;
var spacesDifference = updatedSpacesBeforeCaret - initialSpacesBeforeCaret;
var updatedLeftParenBeforeCaret = formattedValue.substr(0, start).split('(').length - 1;
var leftParenDifference = updatedLeftParenBeforeCaret - initialLeftParenBeforeCaret;
var updatedRightParenBeforeCaret = formattedValue.substr(0, start).split(')').length - 1;
var rightParenDifference = updatedRightParenBeforeCaret - initialRightParenBeforeCaret;
// Note: this will call _onValueChanged again, which will move the
// cursor to the end of the value. Correctly adjust the caret afterwards.
this.updateValueAndPreserveCaret(formattedValue.trim());
// Advance or back up the caret based on the change that happened before it.
this.$.input.selectionStart = this.$.input.selectionEnd = start + spacesDifference + dashesDifference + leftParenDifference + rightParenDifference;
this._handleAutoValidate();
},
/**
* Overidden from Polymer.PaperInputBehavior.
*/
validate: function() {
// Update the container and its addons (i.e. the custom error-message).
var valid = this.$.input.validate()
this.$.container.invalid = !valid;
this.$.container.updateAddons({
inputElement: this.$.input,
value: this.value,
invalid: !valid
});
return valid;
},
/**
* Overidden from Polymer.IronControlState.
*/
_onFocusedChanged: function(focused) {
if (!focused) {
this._handleAutoValidate();
}
}
});
</script>
</dom-module>