Material.io web: Toggle TextField error state

Viewed 1657

I am using material.io Text Field components for a simple web form:

enter image description here

HTML (just for the email field to keep it short)

<div class="inline-text-field-container">
  <div class="tf-email mdc-text-field mdc-text-field--outlined">
    <input class="mdc-text-field__input" id="email" />
    <div class="mdc-notched-outline">
      <div class="mdc-notched-outline__leading"></div>
      <div class="mdc-notched-outline__notch">
        <label for="email" class="mdc-floating-label">Email</label>
      </div>
      <div class="mdc-notched-outline__trailing"></div>
    </div>
  </div>
  <div class="mdc-text-field-helper-line">
    <div
      class="mdc-text-field-helper-text mdc-text-field-helper-text--validation-msg"
      role="alert"
      aria-hidden="true"
    >
      Please enter your email
    </div>
  </div>
</div>

JavaScript

import { MDCTextField } from '@material/textfield';
import { MDCRipple } from '@material/ripple';
import { MDCTextFieldHelperText } from '@material/textfield/helper-text';

const tfEmail = new MDCTextField(document.querySelector('.tf-email'));
const tfPassword = new MDCTextField(document.querySelector('.tf-password'));
const btnSubmit = new MDCRipple(document.querySelector('.mdc-button'));

document.querySelector('.btn-submit').addEventListener('click', onSubmitHandler);

function onSubmitHandler(e) {
    // Validations happen here
    // How do I change the email field's state to a validation error and show the validation text?
}

I can't find any working examples of how to add error validation states to the TextField component (the red outline) and display the help text "Invalid email address" (as per the screenshot).

Can you push me in the right direction?

2 Answers

I am not using the node version rather the web version but I was able to do it using TEXTFIELD.valid = true/false and TEXTFIELD.helperTextContent = 'Short, descriptive content';. For example

TEXTFILED.listen('input', function(){
  TEXTFILED.helperText_.foundation.setPersistent(true);

  if(TEXTFILED.value.length < 4) {
    TEXTFILED.valid = false;
    TEXTFILED.helperTextContent = 'Too short';
    return;
  }
  
  if(TEXTFILED.value.length > 16) {
    TEXTFILED.valid = false;
    TEXTFILED.helperTextContent = 'Too long';
    return;
  }

  TEXTFILED.valid = true;

  TEXTFILED.helperText_.foundation.setPersistent(false);
  // or
  TEXTFILED.helperTextContent = 'Valid';
});

I've been looking into the same. By scouting google i ended up using a TextFormField where i had acces to the validate method

Related