formv

5.4.0 • Public • Published
Formv

React form validation using the validation native to all recent browsers. Also includes support for handling API validation messages, success messages, memoized and nested form state, and super easy styling.

Travis   npm   License MIT   Coveralls   code style: prettier


Contents

  1. Getting Started
  2. Customising Messages
  3. Skipping Validation
  4. JS Validation
  5. API Validation
  6. Success Messages
  7. Managing State
  8. Form Architecture

Getting Started

Formv utilises the native form validation which is built-in to all recent browsers – as such, all validation rules are set on the relevant form fields using required, pattern, minLength, etc...

Formv has a philosophy that it should be easy to opt-out of form validation if and when you want to use another technique in the future. That means not coupling your validation to a particular method, which makes it easily reversible – that is why Formv comes with only one fundamental React component – Form.

To get started you need to append the form to the DOM. Formv's Form component is a plain form element that intercepts the onSubmit function. We then nest all of our input fields in the Form component as you would normally. Form takes an optional function child as a function to pass the form's state – you can also use the context API for more complex forms.

In the examples below we'll take a simple form that requires a name, email and an age. We'll add the front-end validation, capture any back-end validation errors, and show a success message when everything has been submitted.

import { Form, Messages } from 'formv';
 
export default function MyForm() {
    return (
        <Form onSubmitted={handleSubmitted}>
            {({ isDirty, isSubmitting, feedback }) => (
                <>
                    <Messages value={feedback.success} />
                    <Messages value={feedback.error} />
 
                    <input type="text" name="name" required />
                    <Messages values={feedback.field.name} />
 
                    <input type="email" name="email" required />
                    <Messages values={feedback.field.email} />
 
                    <input name="age" required min={18} />
                    <Messages values={feedback.field.age} />
 
                    <button disabled={!isDirty} type="submit">
                        {isSubmitting ? 'Submitting...' : 'Submit'}
                    </button>
                </>
            )}
        </Form>
    );
}

Note: isDirty is an opt-in with the withDirtyCheck prop as it causes form data comparisons upon form change.

Voila! Using the above code you have everything you need to validate your form. By clicking the button all validation rules will be checked, and if you've not filled in the required fields then you'll see a message appear next to the relevant input fields. We are also using the isSubmitting to determine when the form is in the process of being submitted – including any async API requests, and also a dirty check to determine if the form data has been modified from its original state.

Customising Messages

It's good and well relying on the native validation, but if you were to look in different browsers, each validation message would read slightly differently – which is awful for applications that strive for consistency! In those cases the Form component accepts a messages which is a map of the ValidityState object. By using the messages prop we can provide consistent messages across all browsers.

import { Form, Messages } from 'formv';
 
const messages = {
    name: { valueMissing: 'Please enter your first and last name.' },
    email: {
        valueMissing: 'Please enter your email address.',
        typeMismatch: 'Please enter a valid email address.',
    },
    age: {
        valueMissing: 'Please enter your age.',
        rangeUnderflow: 'You must be 18 or over to use this form.',
    },
};
 
<Form messages={messages} onSubmitted={handleSubmitted} />;

Now when you submit the form in Chrome, Firefox, Edge, Safari, Opera, etc... you will note that all of the messages appear the same – you're no longer allowing the browser to control the content of the validation messages.

Skipping Validation

There are some instances where skipping validation might be beneficial. Although you can't skip the back-end validation from Formv directly — you should configure your back-end to accept an optional param that skips validation — it's quite easy to skip the front-end validation by introducing another button element with the native formnovalidate attribute.

In the above form if you were to add another button alongside our existing button, you can have one button that runs the front-end validation in its entirety, and another button that skips it altogether.

<button type="submit">Submit</button>
<button type="submit" formNoValidate>Submit Without Validation</button>

Interestingly when you tap enter in a form, the first button in the DOM hierarchy will be the button that's used to submit the form; in the above case enter would run the validation. However if you were to reverse the order of the buttons in the DOM, the enter key will submit the form without the front-end validation.

JS Validation

For the most part the native HTML validation is sufficient for our forms, especially when you consider the power that the pattern attribute provides with regular expression based validation. Nevertheless there will always be edge-cases where HTML validation doesn't quite cut the mustard. In those cases Formv provides the Error.Validation and Error.Generic exceptions that you can raise during the onSubmitting phase.

import { Form, Error } from 'formv';
import * as utils from './utils';
 
const handleSubmitting = () => {
 
    if (!utils.passesQuirkyValidation(state)) {
        throw new Error.Validation({
            name: 'Does not pass our quirky validation rules.'
        });
    }
 
});
 
<Form onSubmitting={handleSubmitting} />

It's worth noting that any errors that are thrown from the onSubmitting handler will be merged with the native HTML validation messages.

API Validation

It's all good and well having the front-end validation for your forms, however there are always cases where the front-end validation passes just fine, whereas the back-end throws a validation error – maybe the username is already taken, for instance. In those cases we need to feed the API validation messages back into the Form component by using the Error.Validation exception that Formv exports.

The validation messages need to be flattened and should map to your field names – for cases where you have an array of fields, we recommend you name these names.0.firstName, names.1.firstName, etc... Note that we have a flattening helper for Django Rest Framework (DRF) under parse.django.flatten.

Continuing from the above example, we'll implement the handleSubmitted function which handles the submitting of the data to the API.

import { Form, Error } from 'formv';
 
async function handleSubmitted() {
    try {
        await api.post('/send', data);
    } catch (error) {
        const isBadRequest = error.response.status === 400;
        if (isBadRequest) throw new Error.Validation(error.response.data);
        throw error;
    }
}
 
<Form onSubmitted={handleSubmitted} />;

In the example above we're capturing all API errors – we then check if the status code is a 400 which indicates a validation error in our application, and then feeds the validation errors back into Formv. The param passed to the Error.Validation should be a map of errors that correspond to the name attributes in your fields – we will then show the messages next to the relevant fields – for instance the error.response.data may be the following from the back-end if we were to hard-code it on the front-end.

throw new Error.Validation({
    name: 'Please enter your first and last name.',
    age: 'You must be 18 or over to use this form.',
});

However there may be another error code that indicates a more generic error, such as that we weren't able to validate the user at this present moment – perhaps there's an error in our back-end code somewhere. In those cases you can instead raise a Error.Generic to provide helpful feedback to the user.

import { Form, Error } from 'formv';
 
async function handleSubmitted() {
    try {
        await api.post('/send', data);
    } catch (error) {
        const isBadRequest = error.response.status === 400;
        const isAxiosError = error.isAxiosError;
 
        if (isBadRequest) throw new Error.Validation(error.response.data);
        if (isAxiosError) throw new Error.Generic(error.response.data);
        throw error;
    }
}
 
<Form onSubmitted={handleSubmitted} />;

Using the above example we throw Error.Validation errors when the request yields a 400 error message, we raise a Error.Generic error when the error is Axios specific. Any other errors are re-thrown for capturing elsewhere, as they're likely to indicate non-request specific errors such as syntax errors and non-defined variables.

Success Messages

With all the talk of validation errors and generic errors, it may have slipped your mind that sometimes forms submit successfully! In your onSubmitted callback all you need to do is instantiate Success with the content set to some kind of success message.

import { Form, Success, Error } from 'formv';
 
async function handleSubmitted() {
    try {
        await api.post('/send', data);
        return new Success('Everything went swimmingly!');
    } catch (error) {
        const isBadRequest = error.response.status === 400;
        const isAxiosError = error.isAxiosError;
 
        if (isBadRequest) throw new Error.Validation(error.response.data);
        if (isAxiosError) throw new Error.Generic(error.response.data);
        throw error;
    }
}
 
<Form onSubmitted={handleSubmitted} />;

Managing State

Managing the state for your forms is not typically an arduous task, nevertheless there are techniques that can make everything just a little bit easier, which is why Formv exports a useMap hook that has the same interface as react-use's useMap hook with a handful of differences – currying, memoization and nested properties.

import { useMap } from 'formv';
 
const [state, { set }] = useMap({
    username: null,
    profile: {
        age: null,
        created: null,
    },
});

Using the set function provided by useMap you can use a curried function to pass to your Input component. Interestingly if you use the approach below rather than creating a new function every time, the set('username') will never change, and as such makes everything a whole lot easier when it comes to wrapping your Input field in memo.

<Input value={state.username} onChange={set('username')} />
<Input value={state.profile.age} onChange={set('profile.age')} />
<Input value={state.profile.created} onChange={set('profile.created')} />

In contrast, if you were to use the non-curried version – which works perfectly fine and is illustrated below – each time the component is rendered you'd be creating a new function which would cause the component to re-render even when it didn't need to. In an ideal scenario the component would only re-render when its value was modified.

<Input value={state.username} onChange={({ target }) => set('username', target.value)} />

You'll also notice that nested objects are handled with the dot notation thanks to Lodash.

Form Architecture

When deciding on an architecture for your forms, it's recommended to think about them as three separate layers. The first and most simple layer is the field which handles logic pertaining to an individual input field; it can maintain its own state such as a country selector maintains its state for a list of countries, but it does not maintain state for its value. Secondly there is the fieldset layer which composes many field components and is again stateless. Last of all there is the parent form component which maintains state for the entire form.

With the above architecture it allows your field and fieldset components to be used freely in any form components without any quirky state management. The form field has the ultimate responsibility of maintaining and submitting the data.

Using Formv it's easy to have the aforementioned setup as illustrated below.

import * as fv from 'formv';
 
function Form() {
    const [state, { set }] = fv.useMap({
        name: null,
        age: null,
    });
 
    return (
        <fv.Form onSubmitted={handleSubmitted}>
            {({ feedback }) => (
                <>
                    <fv.Messages value={feedback.success} />
                    <fv.Messages value={feedback.error} />
 
                    <Fieldset onChange={set} />
                </>
            )}
        </fv.Form>
    );
}
function Fieldset({ onChange }) {
    return (
        <>
            <FieldName onChange={onChange('name')} />
            <FieldAge onChange={onChange('age')} />
        </>
    );
}
import * as fv from 'formv';
 
function FieldName({ onChange }) {
    const { feedback } = fv.useState();
 
    return (
        <>
            <input name="name" type="text" onChange={({ target }) => onChange(target.value)} />
            <fv.Messages values={feedback.field.name} />
        </>
    );
}
import * as fv from 'formv';
 
function FieldAge({ onChange }) {
    const { feedback } = fv.useState();
 
    return (
        <>
            <input name="age" type="number" onChange={({ target }) => onChange(target.value)} />
            <fv.Messages values={feedback.field.age} />
        </>
    );
}

Readme

Keywords

none

Package Sidebar

Install

npm i formv

Weekly Downloads

107

Version

5.4.0

License

MIT

Unpacked Size

1.99 MB

Total Files

36

Last publish

Collaborators

  • wildhoney