Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@material/mwc-textfield

Package Overview
Dependencies
Maintainers
17
Versions
705
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@material/mwc-textfield

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

  • 0.9.1
  • Source
  • npm
  • Socket score

Version published
Maintainers
17
Created
Source

<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

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 Edge and IE11. See here for detailed instructions.

Example usage

Standard / Filled

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

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

Icon - Leading

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

<script type="module">
  import '@material/mwc-textfield';
  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>
Shaping Outlined
<style>
  mwc-textfield.left {
    --mdc-notched-outline-leading-width: 28px;
    --mdc-notched-outline-leading-border-radius: 28px 0 0 28px;
  }

  mwc-textfield.right {
    --mdc-notched-outline-trailing-border-radius: 0 28px 28px 0;
  }
</style>

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

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

<mwc-textfield
    class="left right";
    label="My Textfield"
    iconTrailing="delete"
    outlined>
</mwc-textfield>

Fullwidth

<!-- Note: Fullwidth does not support label; only placeholder -->
<mwc-textfield fullwidth placeholder="Standard" helper="Helper Text"></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.
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.
fullwidthbooleanWhether or not to make the input fullwidth. No longer displays label; only placeholder and helper.
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)
min`numberstring`
max`numberstring`
step`numbernull`
validityValidityState (readonly)The ValidityState of the textfield.
willValidateboolean (readonly)HTMLInputElement.prototype.willValidate
validityTransform`ValidityTransform**null`
validateOnInitialRenderbooleanRuns validation check on initial render.

* 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>

Methods

NameDescription
checkValidity() => booleanReturns true if the textfield passes validity checks. Returns false and fires an invalid event on the textfield otherwise.
reportValidity() => booleanRuns checkValidity() method, and if it returns false, then ir 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 froma 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-theme-primary#6200eeColor when active of the underline ripple, the outline, and the caret.
--mdc-theme-error#b00020Color when errored of the underline, the outline, the caret, and the icons.
--mdc-text-field-filled-border-radius4px 4px 0 0Border radius of the standard / filled textfield's background filling.
--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.

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

FAQs

Package last updated on 30 Sep 2019

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc