How do I use the pattern parameter of the Polaris component TextField

Highlighted
Shopify Partner
30 0 1

Hi,

 

I have a TextField component of type "email".

I would like to use the pattern parameter of this component, to ensure the entered email address is valid.

When I add a regular expression in the pattern parameter, nothing happens though when I violate the regular expression. I can see I can use the "error" component to show error messages, but how do I combine this with the pattern parameter such that an error message is displayed when the pattern is violated?
(I tried pattern="[0-9]+" and violated that by entering text)

 

Thanks,

-Louise

0 Likes
Shopify Partner
1843 172 547

Polaris doesn't manage state. They're expected to be controlled components. For general guidance on validation see this part of documentation.

 

Sandbox example to illustrate what they and I mean.

 

Code for posterity

import React, { Fragment } from "react";
import { TextField, InlineError } from "@shopify/polaris";

export default class EmailFieldExample extends React.Component {
  state = {
    value: "tester@test.com"
  };

  handleChange = value => {
    this.setState({ value });
  };

  isInvalid = (value, pattern) => {
    if (!value) {
      return true;
    }
    return !new RegExp("^" + pattern + "$").test(value);
  };

  render() {
    const { value } = this.state;
    const emailFieldID = "email";
    // According to W3C, but it has more holes than a Swiss cheese i.e. DO NOT use
    const emailFieldPattern =
      "[a-z0-9!#$%&'*+/=?^_`{|}~.-]+@[a-z0-9-]+(.[a-z0-9-]+)*";
    const isInvalid = this.isInvalid(value, emailFieldPattern);
    const errorMessage = isInvalid ? "Invalid email entered!" : "";

    return (
      <Fragment>
        <TextField
          label="Email"
          type="email"
          value={value}
          pattern={emailFieldPattern}
          onChange={this.handleChange}
        />
        <InlineError message={errorMessage} fieldID={emailFieldID} />
      </Fragment>
    );
  }
}

Best wishes!

I turn coffee in to code - since 1998
0 Likes