UNPKG

15.2 kBMarkdownView Raw
1# `<mwc-textfield>` [![Published on npm](https://img.shields.io/npm/v/@material/mwc-textfield.svg)](https://www.npmjs.com/package/@material/mwc-textfield)
2> IMPORTANT: The Material Web Components are a work in progress and subject to
3> major changes until 1.0 release.
4
5Text fields let users enter and edit text.
6
7<img src="https://raw.githubusercontent.com/material-components/material-components-web-components/06b516b7f91867acd0cbe5676767aea8f490cbee/packages/textfield/images/standard.png" width="244px">
8
9[Material Design Guidelines: text fields](https://material.io/design/components/text-fields.html)
10
11[Demo](https://material-components.github.io/material-web/demos/textfield/)
12
13## Installation
14
15```sh
16npm install @material/mwc-textfield
17```
18
19> NOTE: The Material Web Components are distributed as ES2017 JavaScript
20> Modules, and use the Custom Elements API. They are compatible with all modern
21> browsers including Chrome, Firefox, Safari, Edge, and IE11, but an additional
22> tooling step is required to resolve *bare module specifiers*, as well as
23> transpilation and polyfills for IE11. See
24> [here](https://github.com/material-components/material-components-web-components#quick-start)
25> for detailed instructions.
26
27## Example usage
28
29### Standard / Filled
30
31<img src="https://raw.githubusercontent.com/material-components/material-components-web-components/06b516b7f91867acd0cbe5676767aea8f490cbee/packages/textfield/images/standard.png" width="244px">
32
33```html
34<mwc-textfield label="My Textfield"></mwc-textfield>
35
36<script type="module">
37 import '@material/mwc-textfield/mwc-textfield.js';
38</script>
39```
40
41### Icon - Leading
42
43<img src="https://raw.githubusercontent.com/material-components/material-components-web-components/06b516b7f91867acd0cbe5676767aea8f490cbee/packages/textfield/images/icon-leading.png" width="244px">
44
45```html
46<mwc-textfield label="My Textfield" icon="event"></mwc-textfield>
47
48<script type="module">
49 import '@material/mwc-textfield/mwc-textfield.js';
50 import '@material/mwc-icon/mwc-icon-font.js';
51</script>
52```
53
54### Icon - Trailing
55
56<img src="https://raw.githubusercontent.com/material-components/material-components-web-components/06b516b7f91867acd0cbe5676767aea8f490cbee/packages/textfield/images/icon-trailing.png" width="244px">
57
58```html
59<mwc-textfield label="My Textfield" iconTrailing="delete"></mwc-textfield>
60```
61
62### Helper Text
63
64<img src="https://raw.githubusercontent.com/material-components/material-components-web-components/06b516b7f91867acd0cbe5676767aea8f490cbee/packages/textfield/images/helper.png" width="244px">
65
66```html
67<mwc-textfield label="My Textfield" helper="Helper Text"></mwc-textfield>
68```
69
70### Primary Color
71
72<img src="https://raw.githubusercontent.com/material-components/material-components-web-components/06b516b7f91867acd0cbe5676767aea8f490cbee/packages/textfield/images/color-primary.png" width="244px">
73
74```html
75<style>
76 mwc-textfield {
77 --mdc-theme-primary: green;
78 }
79</style>
80
81<mwc-textfield
82 label="My Textfield"
83 iconTrailing="delete"
84 required>
85</mwc-textfield>
86```
87
88## Variants
89
90### Outlined
91
92<img src="https://raw.githubusercontent.com/material-components/material-components-web-components/06b516b7f91867acd0cbe5676767aea8f490cbee/packages/textfield/images/outlined.png" width="244px">
93
94```html
95<mwc-textfield
96 outlined
97 label="My Textfield"
98 iconTrailing="delete">
99</mwc-textfield>
100```
101
102#### Shaped
103
104<img src="https://raw.githubusercontent.com/material-components/material-components-web-components/06b516b7f91867acd0cbe5676767aea8f490cbee/packages/textfield/images/shape.png" width="233px">
105
106```html
107<style>
108 mwc-textfield.rounded {
109 --mdc-shape-small: 28px;
110 }
111</style>
112
113<mwc-textfield
114 class="rounded"
115 label="My Textfield"
116 outlined>
117</mwc-textfield>
118```
119
120## API
121
122### Properties/Attributes
123
124Name | Type | Description
125------------------------- | ----------------------------- | -----------
126`value` | `string` | The input control's value.
127`type` | `TextFieldType*` | A string specifying the type of control to render.
128`label` | `string` | Sets floating label value.
129`placeholder` | `string` | Sets disappearing input placeholder.
130`prefix` | `string` | Prefix text to display before the input.
131`suffix` | `string` | Suffix text to display after the input.
132`icon` | `string` | Leading icon to display in input. See [`mwc-icon`](https://github.com/material-components/material-web/tree/master/packages/icon).
133`iconTrailing` | `string` | Trailing icon to display in input. See [`mwc-icon`](https://github.com/material-components/material-web/tree/master/packages/icon).
134`disabled` | `boolean` | Whether or not the input should be disabled.
135`charCounter` | `boolean` | **Note: requries `maxLength` to be set.** Display character counter with max length.
136`outlined` | `boolean` | Whether or not to show the material outlined variant.
137`helper` | `string` | Helper text to display below the input. Display default only when focused.
138`helperPersistent` | `boolean` | Always show the helper text despite focus.
139`required` | `boolean` | Displays error state if value is empty and input is blurred.
140`maxLength` | `number` | Maximum length to accept input.
141`validationMessage` | `string` | Message to show in the error color when the textfield is invalid. (Helper text will not be visible)
142`pattern` | `string` | [`HTMLInputElement.prototype.pattern`](https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/HTML5/Constraint_validation#Validation-related_attributes) (empty string will unset attribute)
143`min` | `number`\|`string` | [`HTMLInputElement.prototype.min`](https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/HTML5/Constraint_validation#Validation-related_attributes) (empty string will unset attribute)
144`max` | `number`\|`string` | [`HTMLInputElement.prototype.max`](https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/HTML5/Constraint_validation#Validation-related_attributes) (empty string will unset attribute)
145`size` | `number`\|`null` | [`HTMLInputElement.prototype.size`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#htmlattrdefsize) (null will unset attribute)
146`step` | `number`\|`null` | [`HTMLInputElement.prototype.step`](https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/HTML5/Constraint_validation#Validation-related_attributes) (null will unset attribute)
147`autoValidate` | `boolean` | Reports validity on value change rather than only on blur.
148`validity` | `ValidityState` (readonly) | The [`ValidityState`](https://developer.mozilla.org/en-US/docs/Web/API/ValidityState) of the textfield.
149`willValidate` | `boolean` (readonly) | [`HTMLInputElement.prototype.willValidate`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement#Properties)
150`validityTransform` | `ValidityTransform**`\|`null` | Callback called before each validation check. See the [validation section](#Validation) for more details.
151`validateOnInitialRender` | `boolean` | Runs validation check on initial render.
152`name` | `string` | Sets the `name` attribute on the internal input.\*\*\*
153
154\* `TextFieldType` is exported by `mwc-textfield` and `mwc-textfield-base`
155```ts
156type TextFieldType = 'text'|'search'|'tel'|'url'|'email'|'password'|
157 'date'|'month'|'week'|'time'|'datetime-local'|'number'|'color';
158```
159
160\*\* `ValidityTransform` is not exported. See the [validation section](#Validation) for more details.
161```ts
162type ValidityTransform = (value: string, nativeValidity: ValidityState) => Partial<ValidityState>
163```
164
165\*\*\* The `name` property should only be used for browser autofill as webcomponent form participation does not currently consider the `name` attribute. See [#289](https://github.com/material-components/material-components-web-components/issues/289).
166
167### Methods
168
169| Name | Description
170| -------- | -------------
171| `checkValidity() => boolean` | Returns `true` if the textfield passes validity checks. Returns `false` and fires an [`invalid`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/invalid_event) event on the textfield otherwise. <br>**NOTE:** When accessing any property or function that checks validity at textfield initial boot up, you may have to await `<mwc-textfield>.updateComplete`.
172| `reportValidity() => boolean` | Runs `checkValidity()` method, and if it returns false, then it reports to the user that the input is invalid.
173| `setCustomValidity(message:string) => void` | Sets a custom validity message (also overwrites `validationMessage`). If this message is not the empty string, then the element is suffering from a custom validity error and does not validate.
174| `layout() => Promise<void>` | Re-calculate layout. If a textfield is styled with `display:none` before it is first rendered, and it has a label that is floating, then you must call `layout()` the first time you remove `display:none`, or else the notch surrounding the label will not render correctly.
175
176### CSS Custom Properties
177
178Inherits CSS Custom properties from:
179
180* [`mwc-ripple`](https://github.com/material-components/material-web/tree/master/packages/ripple)
181* [`mwc-notched-outline`](https://github.com/material-components/material-web/tree/master/packages/notched-outline).
182* [`mwc-icon`](https://github.com/material-components/material-web/tree/master/packages/icon)
183
184| Name | Default | Description
185| ------------------------------------------------- | --------------------- |------------
186| `--mdc-text-field-filled-border-radius` | `4px 4px 0 0` | Border radius of the standard / filled textfield's background filling.
187| `--mdc-text-field-idle-line-color` | `rgba(0, 0, 0, 0.42)` | Color of the filled textfield's bottom line when idle.
188| `--mdc-text-field-hover-line-color` | `rgba(0, 0, 0, 0.87)` | Color of the filled textfield's bottom line when hovering.
189| `--mdc-text-field-disabled-line-color` | `rgba(0, 0, 0, 0.06)` | Color of the filled textfield's bottom line when disabled.
190| `--mdc-text-field-outlined-idle-border-color` | `rgba(0, 0, 0, 0.38)` | Color of the outlined textfield's outline when idle.
191| `--mdc-text-field-outlined-hover-border-color` | `rgba(0, 0, 0, 0.87)` | Color of the outlined textfield's outline when hovering.
192| `--mdc-text-field-outlined-disabled-border-color` | `rgba(0, 0, 0, 0.06)` | Color of the outlined textfield's outline when disabled.
193| `--mdc-text-field-fill-color` | `rgb(245, 245, 245)` | Color of the textfield's background fill (non-outlined).
194| `--mdc-text-field-disabled-fill-color` | `rgb(250, 250, 250)` | Color of the textfield's background fill (non-outlined) when disabled.
195| `--mdc-text-field-ink-color` | `rgba(0, 0, 0, 0.87)` | Color of the input text.
196| `--mdc-text-field-label-ink-color` | `rgba(0, 0, 0, 0.6)` | Color of the non-focused floating label, helper text, char counter, and placeholder.
197| `--mdc-text-field-disabled-ink-color` | `rgba(0, 0, 0, 0.37)` | Color of the input text, the floating label, helper text, char counter, and placeholder of a disabled textfield.
198
199#### Global Custom Properties
200
201This component exposes the following global [theming](https://github.com/material-components/material-components-web-components/blob/master/docs/theming.md)
202custom properties.
203
204| Name | Description
205| -------------------- | -----------
206| `--mdc-theme-primary` | Color when active of the underline ripple, the outline, and the caret.
207| `--mdc-theme-error` | Color when errored of the underline, the outline, the caret, and the icons.
208| `--mdc-typography-subtitle1-<PROPERTY>` | Styles the typography of the textfield.
209
210### Validation
211
212`<mwc-textfield>` follows the basic `<input>` [constraint validation model](https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/HTML5/Constraint_validation).
213It exposes:
214
215* `required`
216* `maxLength`
217* `pattern`
218* `min`
219* `max`
220* `step`
221* `validity`
222* `willValidate`
223* `checkValidity()`
224* `reportValidity()`
225* `setCustomValidity(message)`
226
227Additionally, it implements more features such as:
228
229* `validationMessage`
230* `validateOnInitialRender`
231* and `validityTransform`
232
233By default, `<mwc-textfield>` will report validation on `blur`.
234
235#### Custom validation logic
236
237The `validityTransform` property is a function that can be set on `<mwc-textfield>` to
238implement custom validation logic that transforms the `ValidityState` of the
239input control. The type of a `ValidityTransform` is the following:
240
241```ts
242(value: string, nativeValidity: ValidityState) => Partial<ValidityState>
243```
244
245Where `value` is the new value in the textfield to be validated and
246`nativeValidity` is an interface of
247[`ValidityState`](https://developer.mozilla.org/en-US/docs/Web/API/ValidityState)
248of the native input control. For example:
249
250```html
251<mwc-textfield
252 id="my-textfield"
253 pattern="[0-9]+"
254 value="doggos">
255</mwc-textfield>
256<script>
257 const textfield = document.querySelector('#my-textfield');
258 textfield.validityTransform = (newValue, nativeValidity) => {
259 if (!nativeValidity.valid) {
260 if (nativeValidity.patternMismatch) {
261 const hasDog = newValue.includes('dog');
262 // changes to make to the nativeValidity
263 return {
264 valid: hasDog,
265 patternMismatch: !hasDog;
266 };
267 } else {
268 // no changes
269 return {};
270 }
271 } else {
272 const isValid = someExpensiveOperation(newValue);
273 // changes to make to the native validity
274 return {
275 valid: isValid,
276 // or whatever type of ValidityState prop you would like to set (if any)
277 customError: !isValid,
278 };
279 }
280 }
281</script>
282```
283
284In this example we first check the native validity which is invalid due to the
285pattern mismatching (the value is `doggos` which is not a number). The value
286includes `dog`, thus we make it valid and undo the pattern mismatch.
287
288In this example, we also skip an expensive validity check by short-circuiting
289the validation by checking the native validation.
290
291*Note:* the UI will only update as valid / invalid by checking the `valid`
292property of the transformed `ValidityState`.
293
294## Additional references
295
296- [MDC Web textfields](https://material.io/develop/web/components/input-controls/text-field/)