Giter Club home page Giter Club logo

react-formatted-input's Introduction

react-formatted-input

An input component that abides by configurable formatting and constraint rules

Build Status npm package

About

FormattedInput takes a value and ensures that user input conforms to some specified rules. Formatted input instances can have their length limited, as well as having a pattern enforced for their entry. As the user types, changes to the value are forced through the provided pattern and any sections that are invalid are simply stripped. What is returned from the component is a pattern-matched string.

This is useful for custom inputs that are designed to take values of a certain type, often mapping to real world information like credit card details or dates.

Installation

To install, simply run npm install @buttercup/react-formatted-input --save or yarn add @buttercup/react-formatted-input.

Development

You can run the Storybook to test the component in your browser, by executing npm run storybook.

Usage

Import the FormattedInput class and just drop it in:

import { FormattedInput } from "@buttercup/react-formatted-input";
import React, { Component } from "react";

export default class MyForm extends Component {

    constructor(props) {
        super(props);
        this.state = {
            idNumber: ""
        };
    }

    render() {
        const idPattern = [
            { char: /\d/, repeat: 3 },
            { exactly: "-" },
            { char: /\d/, repeat: 2 },
            { char: /[a-z]/i }
        ];
        return (
            <form>
                <FormattedInput
                    className="formatted-input"
                    format={idPattern}
                    value={this.state.idNumber}
                    onChange={(formattedValue, raw) => { this.state.idNumber = formattedValue; }}
                    placeholder="ID in format: NNN-NNL"
                    />
            </form>
        );
    }

}

There is also a FormattedText class which simply outputs a text node:

import React from "react";
import { FormattedText } from "@buttercup/react-formatted-input";

// MM/YYYY
const DateFormat = [
    { char: /[01]/, repeat: 1 },
    { char: /\d/, repeat: 1 },
    { exactly: "/" },
    { char: /2/, repeat: 1 },
    { char: /\d/, repeat: 3 }
];

const MyComponent = () => (
    <span>
        <FormattedText value="01/2019" format={DateFormat} />
    </span>
);

You can also import just the format function:

import { format } from "@buttercup/react-formatted-input";

const USPhoneNumberFormat = [
    { char: /\d/, repeat: 3 },
    { exactly: "-" },
    { char: /\d/, repeat: 3 },
    { exactly: "-" },
    { char: /\d/, repeat: 4 }
];

const { formatted, raw } = format("2025550199", USPhoneNumberFormat);
// formatted = 202-555-0199
// raw = 2025550199

Regular expression alternatives

As Regular Expression instances don't serialise, it's possible to use a string or array to describe the pattern:

const format1 = [{ char: "\\w", repeat: 5 }];

const format2 = [{ char: ["[a-f0-9]", "i"], repeat: 5 }];

The second value in the array is the flag string for the RegExp constructor.

Presets

Some presets are available in the source/presets.js file that might be used like so:

import { FormattedInput, Presets } from "@buttercup/react-formatted-input";
import React, { Component } from "react";

export default class MyForm extends Component {

    render() {
        return (
            <form>
                <FormattedInput
                    format={Presets.CreditCard}
                    value={this.state.creditCardNo}
                    />
                <FormattedInput
                    format={Presets.CreditCardDate}
                    value={this.state.creditCardValidFrom}
                    />
                <FormattedInput
                    format={Presets.CreditCardDate}
                    value={this.state.creditCardExpiry}
                    />
            </form>
        );
    }

}

API

The FormattedInput component can be used without any props, of course, but you might want some of these for it to be useful:

value : String

The initialisation value for the formatted input. This value is still run through the formatting process, so it is possible that the applied value is different to the one provided.

format : Array

The format is a collection of patterns and delimiters that control what values can be entered. By default there is no format (so any input is allowed), but it can be set to an array of objects that are used to process the value upon every change:

  • Character match groups: A character match (char) is a regular expression designed to match just 1 character. It may also contain a repeat property to specify how many characters this pattern should match. repeat defaults to 1 if not specified. For example, { char: /\d/ } will match exactly 1 number, whereas { char: /-/, repeat: 3 } will match 3 dashes.
  • Exact groups: An exact group represents a string or character that must come next in the value. It is used to specify mandatory delimiters in the value. For instance, { exactly: "." } will enforce that a period appears next in the value. Exact groups also support the repeat property. Characters added using exact groups do not appear in raw values.

When used in combination together, complex values like credit-card numbers can be easily represented:

[
    { char: /\d/, repeat: 4 },
    { exactly: "-" },
    { char: /\d/, repeat: 4 },
    { exactly: "-" },
    { char: /\d/, repeat: 4 },
    { exactly: "-" },
    { char: /\d/, repeat: 4 }
]

Or even the expiry date of such a credit card:

[
    { char: /[01]/ },  // month, 2 digits
    { char: /[0-9]/ }, // "
    { exactly: "/" },
    { char: /2/ },                  // year, 4 digits
    { char: /[0-9]/, repeat: 3 }    // "
]

onChange : Function

A callback function for when the value changes. The function receives 2 parameters: the new formatted value and the new raw value, respectively. The function is only called if the formatted value differs from the last one.

type : String

The input type to use (defaults to "text"). The type "password" is also supported, but this disables formatting.

name, placeholder, className

Formatted input instances pass through these props to the underlying <input> element.

react-formatted-input's People

Contributors

perry-mitchell avatar ryandagg avatar sallar avatar saurabhiam avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

react-formatted-input's Issues

Strict mode (match entirety)

Support for strictly matching the entire string - perhaps an extra callback parameter to say when the entire pattern is matched?

Support ref or focus() method

Trying to trigger focus() on the underlying input, however the FormattedInput does not expose it, neither does it pass a ref to the input do to it directly.

Formate date or time use regexp

How to implement formatting input use regex?
For time: ^(0[0-9]|1[0-9]|2[0-3]|[0-9]):[0-5][0-9]$
And date: ^(((0[1-9]|[12]\d|3[01])\.(0[13578]|1[02])\.((19|[2-9]\d)\d{2}))|((0[1-9]|[12]\d|30)\.(0[13456789]|1[012])\.((19|[2-9]\d)\d{2}))|((0[1-9]|1\d|2[0-8])\.02\.((19|[2-9]\d)\d{2}))|(29\.02\.((1[6-9]|[2-9]\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))))$

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.