0.27.0 • Published 2 years ago

@material/mwc-textfield v0.27.0

Weekly downloads
9,543
License
Apache-2.0
Repository
github
Last release
2 years ago

<mwc-textfield> Published on npm

IMPORTANT: The Material Web Components are a work in progress and subject to major changes until 1.0 release.

Text fields let users enter and edit text.

Material Design Guidelines: text fields

Demo

Installation

npm install @material/mwc-textfield

NOTE: The Material Web Components are distributed as ES2017 JavaScript Modules, and use the Custom Elements API. They are compatible with all modern browsers including Chrome, Firefox, Safari, Edge, and IE11, but an additional tooling step is required to resolve bare module specifiers, as well as transpilation and polyfills for IE11. See here for detailed instructions.

Example usage

Standard / Filled

<mwc-textfield label="My Textfield"></mwc-textfield>

<script type="module">
  import '@material/mwc-textfield/mwc-textfield.js';
</script>

Icon - Leading

<mwc-textfield label="My Textfield" icon="event"></mwc-textfield>

<script type="module">
  import '@material/mwc-textfield/mwc-textfield.js';
  import '@material/mwc-icon/mwc-icon-font.js';
</script>

Icon - Trailing

<mwc-textfield label="My Textfield" iconTrailing="delete"></mwc-textfield>

Helper Text

<mwc-textfield label="My Textfield" helper="Helper Text"></mwc-textfield>

Primary Color

<style>
  mwc-textfield {
    --mdc-theme-primary: green;
  }
</style>

<mwc-textfield
    label="My Textfield"
    iconTrailing="delete"
    required>
</mwc-textfield>

Variants

Outlined

<mwc-textfield
    outlined
    label="My Textfield"
    iconTrailing="delete">
</mwc-textfield>

Shaped

<style>
  mwc-textfield.rounded {
    --mdc-shape-small: 28px;
  }
</style>

<mwc-textfield
    class="rounded"
    label="My Textfield"
    outlined>
</mwc-textfield>

API

Properties/Attributes

NameTypeDescription
valuestringThe input control's value.
typeTextFieldType*A string specifying the type of control to render.
labelstringSets floating label value.
placeholderstringSets disappearing input placeholder.
prefixstringPrefix text to display before the input.
suffixstringSuffix text to display after the input.
iconstringLeading icon to display in input. See mwc-icon.
iconTrailingstringTrailing icon to display in input. See mwc-icon.
disabledbooleanWhether or not the input should be disabled.
charCounterbooleanNote: requries maxLength to be set. Display character counter with max length.
outlinedbooleanWhether or not to show the material outlined variant.
helperstringHelper text to display below the input. Display default only when focused.
helperPersistentbooleanAlways show the helper text despite focus.
requiredbooleanDisplays error state if value is empty and input is blurred.
maxLengthnumberMaximum length to accept input.
validationMessagestringMessage to show in the error color when the textfield is invalid. (Helper text will not be visible)
patternstringHTMLInputElement.prototype.pattern (empty string will unset attribute)
minnumber|stringHTMLInputElement.prototype.min (empty string will unset attribute)
maxnumber|stringHTMLInputElement.prototype.max (empty string will unset attribute)
sizenumber|nullHTMLInputElement.prototype.size (null will unset attribute)
stepnumber|nullHTMLInputElement.prototype.step (null will unset attribute)
autoValidatebooleanReports validity on value change rather than only on blur.
validityValidityState (readonly)The ValidityState of the textfield.
willValidateboolean (readonly)HTMLInputElement.prototype.willValidate
validityTransformValidityTransform**|nullCallback called before each validation check. See the validation section for more details.
validateOnInitialRenderbooleanRuns validation check on initial render.
namestringSets the name attribute on the internal input.***

* TextFieldType is exported by mwc-textfield and mwc-textfield-base

type TextFieldType = 'text'|'search'|'tel'|'url'|'email'|'password'|
    'date'|'month'|'week'|'time'|'datetime-local'|'number'|'color';

** ValidityTransform is not exported. See the validation section for more details.

type ValidityTransform = (value: string, nativeValidity: ValidityState) => Partial<ValidityState>

*** The name property should only be used for browser autofill as webcomponent form participation does not currently consider the name attribute. See #289.

Methods

NameDescription
checkValidity() => booleanReturns true if the textfield passes validity checks. Returns false and fires an invalid event on the textfield otherwise. NOTE: When accessing any property or function that checks validity at textfield initial boot up, you may have to await <mwc-textfield>.updateComplete.
reportValidity() => booleanRuns checkValidity() method, and if it returns false, then it reports to the user that the input is invalid.
setCustomValidity(message:string) => voidSets 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.
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.

CSS Custom Properties

Inherits CSS Custom properties from:

NameDefaultDescription
--mdc-text-field-filled-border-radius4px 4px 0 0Border radius of the standard / filled textfield's background filling.
--mdc-text-field-idle-line-colorrgba(0, 0, 0, 0.42)Color of the filled textfield's bottom line when idle.
--mdc-text-field-hover-line-colorrgba(0, 0, 0, 0.87)Color of the filled textfield's bottom line when hovering.
--mdc-text-field-disabled-line-colorrgba(0, 0, 0, 0.06)Color of the filled textfield's bottom line when disabled.
--mdc-text-field-outlined-idle-border-colorrgba(0, 0, 0, 0.38)Color of the outlined textfield's outline when idle.
--mdc-text-field-outlined-hover-border-colorrgba(0, 0, 0, 0.87)Color of the outlined textfield's outline when hovering.
--mdc-text-field-outlined-disabled-border-colorrgba(0, 0, 0, 0.06)Color of the outlined textfield's outline when disabled.
--mdc-text-field-fill-colorrgb(245, 245, 245)Color of the textfield's background fill (non-outlined).
--mdc-text-field-disabled-fill-colorrgb(250, 250, 250)Color of the textfield's background fill (non-outlined) when disabled.
--mdc-text-field-ink-colorrgba(0, 0, 0, 0.87)Color of the input text.
--mdc-text-field-label-ink-colorrgba(0, 0, 0, 0.6)Color of the non-focused floating label, helper text, char counter, and placeholder.
--mdc-text-field-disabled-ink-colorrgba(0, 0, 0, 0.37)Color of the input text, the floating label, helper text, char counter, and placeholder of a disabled textfield.

Global Custom Properties

This component exposes the following global theming custom properties.

NameDescription
--mdc-theme-primaryColor when active of the underline ripple, the outline, and the caret.
--mdc-theme-errorColor when errored of the underline, the outline, the caret, and the icons.
--mdc-typography-subtitle1-<PROPERTY>Styles the typography of the textfield.

Validation

<mwc-textfield> follows the basic <input> constraint validation model. It exposes:

  • required
  • maxLength
  • pattern
  • min
  • max
  • step
  • validity
  • willValidate
  • checkValidity()
  • reportValidity()
  • setCustomValidity(message)

Additionally, it implements more features such as:

  • validationMessage
  • validateOnInitialRender
  • and validityTransform

By default, <mwc-textfield> will report validation on blur.

Custom validation logic

The validityTransform property is a function that can be set on <mwc-textfield> to implement custom validation logic that transforms the ValidityState of the input control. The type of a ValidityTransform is the following:

(value: string, nativeValidity: ValidityState) => Partial<ValidityState>

Where value is the new value in the textfield to be validated and nativeValidity is an interface of ValidityState of the native input control. For example:

<mwc-textfield
    id="my-textfield"
    pattern="[0-9]+"
    value="doggos">
</mwc-textfield>
<script>
  const textfield = document.querySelector('#my-textfield');
  textfield.validityTransform = (newValue, nativeValidity) => {
    if (!nativeValidity.valid) {
      if (nativeValidity.patternMismatch) {
        const hasDog = newValue.includes('dog');
        // changes to make to the nativeValidity
        return {
          valid: hasDog,
          patternMismatch: !hasDog;
        };
      } else {
        // no changes
        return {};
      }
    } else {
      const isValid = someExpensiveOperation(newValue);
      // changes to make to the native validity
      return {
        valid: isValid,
        // or whatever type of ValidityState prop you would like to set (if any)
        customError: !isValid,
      };
    }
  }
</script>

In this example we first check the native validity which is invalid due to the pattern mismatching (the value is doggos which is not a number). The value includes dog, thus we make it valid and undo the pattern mismatch.

In this example, we also skip an expensive validity check by short-circuiting the validation by checking the native validation.

Note: the UI will only update as valid / invalid by checking the valid property of the transformed ValidityState.

Additional references

@material/mwc-textareazagenzagen-productionbf-forms@glade-software/glade-annotateable@simplr-wc/email-input@simplr-wc/number-input@simplr-wc/password-input@simplr-wc/text-inputsimplr-components@netzoio/web-componentsopenstamanager@everything-registry/sub-chunk-584@boluabraham/fhir-loginopen-scd@erixhens/annotatorscoped-material-components@dhruval/autocomplete-selectruhil-uisaby-customizer@backlight-dev/aodocs.aodocs-design-system@binar/search-dialog@bfchain/dweb-browsercloudbees-casc-server-plugin-uiplayground-elementsplayground-elements-ashcorgy-frontend@blackpurl/web-components@boluabraham/fhir-active-status@boluabraham/fhir-create-patient2@boluabraham/fhir-human-address_@boluabraham/fhir-human-contact@boluabraham/fhir-human-language@boluabraham/fhir-human-name@boluabraham/fhir-human-relationboo-wysiwyg-ebpwc-textfieldokiduty-pricing-component@dman777/lit-time-pickercumqueab@allenporter/recurrence-rule-editor@_lucky/app-datepickerfirebase-autoformeth-wallet-connectestdeseruntsyd-form@batchforce/core@esui/material-components@exmg/exmg-searchbar@formsey/fields-material@finastra/textfield@frag-crypto/frag-default-plugins@dwane-vonage/cityjs-india@dwane-vonage/dwanes-keypad@dwane-vonage/vve-text-chat@dwane-vonage/whatever-you-like-keypad@equinor/fusion-wc-searchable-dropdown@equinor/fusion-wc-textinput@pixano/core@jsview/material-components@klingen/location-search@jcdomber/grte-cat-menu@jcdomber/grte-man-cat-menu@jrg-material/material@jrg/ubuntu-ui@maicol07/mwa-data-table@pedrule/moulder-survey@rakoon-badshah/demo-input@roadsync/roadsync-js@openscd/oscd-filtered-list@openscd/oscd-tree-explorer@openscd/oscd-tree-grid@npm_lucky/app-datepicker@near-solution/shell@near-solution/auth-ui@leavittsoftware/titanium-address-input@leavittsoftware/leavitt-elements@leavittsoftware/leavitt-file-explorer@leavittsoftware/titanium-youtube-input@leavittsoftware/titanium-color-input@leavittsoftware/titanium-duration-input@leavittsoftware/titanium-select@lordoftheflies/plutonium-styles@openenergytools/scl-wizardingmwc-bundlemwc-markdown-editor@wces/autocomplete@wces/form-builder@wces/jsui-materialapp-datepickermeteoalarm-card@things-factory/auth-ui@things-factory/auth-ui-jwt@things-factory/shell@things-factory/common@takeramagan/hotel-library@tadevel/decision2021@tadevel/decision2023@viajai/viajai-ds@vonage/vwc-textarea@vonage/vwc-textfield
0.27.0

2 years ago

0.26.1

2 years ago

0.26.0

2 years ago

0.25.3

2 years ago

0.25.2

3 years ago

0.25.1

3 years ago

0.25.0

3 years ago

0.23.0

3 years ago

0.22.1

3 years ago

0.21.0

3 years ago

0.20.0

3 years ago

0.19.1

4 years ago

0.19.0

4 years ago

0.18.0

4 years ago

0.17.2

4 years ago

0.17.0

4 years ago

0.16.1

4 years ago

0.15.0

4 years ago

0.14.1

4 years ago

0.14.0

4 years ago

0.13.0

4 years ago

0.12.0

4 years ago

0.11.1

4 years ago

0.11.0

4 years ago

0.10.0

5 years ago

0.9.1

5 years ago

0.9.0

5 years ago

0.8.0

5 years ago

0.7.1

5 years ago

0.7.0

5 years ago