1.0.0 • Published 6 months ago

react-input-mask-hook v1.0.0

Weekly downloads
-
License
ISC
Repository
github
Last release
6 months ago

react-input-mask-hook

React hook for connecting to the input of a strict/non-strict mask.

Installation

npm i react-input-mask-hook

Parameters

Passes an object with properties as input:

Return value

Hook returns an object with the following properties:

Example

  1. Input type must be equal to text.
  2. The strict: true is transmitted if the number of characters in the mask is unchanged. For example, phone, ip address or your custom mask.
  3. The pattern is passed if you want to use isValid and error.

Strict mask

  const inputRef = useRef<HTMLInputElement>(null);
  const { value, onChange } = useMask({
    inputRef: inputRef,
    mask: "+7 (123) 123-12-13",
    replace: {
      key: /\d/,
      value: /\d/,
    },
    strict: true,
  });

  return (
    <label>
      <input
        type="text"
        value={value}
        onChange={onChange}
        ref={inputRef}
      />
    </label>
  );

In this example, it makes sense to add a pattern for validation, since some characters may be equal to "_".

  const inputRef = useRef<HTMLInputElement>(null);
  const { value, onChange, error, isValid } = useMask({
    inputRef: inputRef,
    mask: "+7 (___) ___-__-__",
    replace: {
      key: /_/,
      value: /\d/,
    },
    strict: true,
    pattern: '\\+\\d\\s\\([\\d]{3}\\)\\s[\\d]{3}-\\d\\d-\\d\\d',
  });

  return (
    <label>
      <input
        type="text"
        value={value}
        onChange={onChange}
        ref={inputRef}
      />
      <span>{error}</span>
    </label>
  );

Non-strict mask

  const inputRef = React.useRef<HTMLInputElement>(null);
  const { value, onChange, error, isValid } = useMask({
    inputRef: inputRef,
    mask: 'pochta@gmail.com',
    replace: {
      key: /[a-z]/i,
      value: /[a-z]/i,
    },
    pattern: '[a-z]+@[a-z]+\\.(ru|com)'
  });

  return (
    <label>
      <input
        type="text"
        value={value}
        onChange={onChange}
        ref={inputRef}
      />
      <span>{error}</span>
    </label>
  );

  const inputRef = React.useRef<HTMLInputElement>(null);
  const { value, onChange, error, isValid } = useMask({
    inputRef: inputRef,
    mask: 'http://*.com',
    replace: {
      key: /\*/,
      value: /[a-z]/,
    },
    pattern: 'http:\\/\\/[a-z]+\\.com'
  });

  return (
    <label>
      <input
        type="text"
        value={value}
        onChange={onChange}
        ref={inputRef}
      />
      <span>{error}</span>
    </label>
  );