├── .babelrc ├── .eslintignore ├── .eslintrc ├── .gitignore ├── .npmignore ├── .prettierignore ├── .prettierrc.json ├── .travis.yml ├── LICENSE ├── README.md ├── ava.config.js ├── example ├── .babelrc ├── images │ ├── information.svg │ └── logo.png ├── index.html ├── js │ ├── components │ │ ├── Field │ │ │ ├── index.js │ │ │ └── styles.js │ │ ├── Form │ │ │ ├── index.js │ │ │ ├── styles.js │ │ │ └── utils.js │ │ ├── Input │ │ │ ├── index.js │ │ │ └── styles.js │ │ ├── Layout │ │ │ ├── index.js │ │ │ └── styles.js │ │ ├── Messages │ │ │ ├── index.js │ │ │ └── styles.js │ │ └── Textarea │ │ │ ├── index.js │ │ │ └── styles.js │ └── index.js ├── server.mjs └── webpack.config.js ├── helpers ├── browser-env.js ├── enzyme.js └── puppeteer.js ├── media └── logo.psd ├── package.json ├── rollup.config.js ├── src ├── components │ ├── Container │ │ ├── __tests__ │ │ │ └── index.js │ │ └── index.js │ ├── Field │ │ ├── __tests__ │ │ │ └── index.js │ │ └── index.js │ ├── Form │ │ ├── __tests__ │ │ │ ├── __snapshots__ │ │ │ │ ├── index.js.md │ │ │ │ ├── index.js.snap │ │ │ │ ├── utils.js.md │ │ │ │ └── utils.js.snap │ │ │ ├── index.js │ │ │ └── utils.js │ │ ├── index.js │ │ └── utils.js │ ├── Messages │ │ ├── __tests__ │ │ │ └── index.js │ │ └── index.js │ └── Store │ │ ├── __tests__ │ │ ├── __snapshots__ │ │ │ ├── index.js.md │ │ │ └── index.js.snap │ │ └── index.js │ │ └── index.js ├── helpers │ └── parse │ │ ├── django │ │ ├── __tests__ │ │ │ ├── __snapshots__ │ │ │ │ ├── index.js.md │ │ │ │ └── index.js.snap │ │ │ └── index.js │ │ └── index.js │ │ └── index.js ├── index.js └── utils │ ├── __tests__ │ ├── __snapshots__ │ │ ├── useMap.js.md │ │ └── useMap.js.snap │ └── useMap.js │ ├── feedback.js │ └── useMap.js ├── tests ├── index.js └── snapshots │ ├── index.js.md │ └── index.js.snap └── yarn.lock /.babelrc: -------------------------------------------------------------------------------- 1 | { 2 | "plugins": [ 3 | [ 4 | "@babel/plugin-transform-runtime", 5 | { 6 | "regenerator": true, 7 | } 8 | ] 9 | ], 10 | "presets": ["@babel/preset-env", "@babel/preset-react"] 11 | } 12 | -------------------------------------------------------------------------------- /.eslintignore: -------------------------------------------------------------------------------- 1 | .history/ 2 | .nyc_output/ 3 | dist/ 4 | example/js/build.js 5 | -------------------------------------------------------------------------------- /.eslintrc: -------------------------------------------------------------------------------- 1 | { 2 | "parser": "babel-eslint", 3 | "extends": ["standard", "prettier", "plugin:react/recommended", "prettier/standard"], 4 | "plugins": ["react"], 5 | "rules": { 6 | "no-sequences": "off", 7 | "no-void": "off", 8 | "react/react-in-jsx-scope": "off", 9 | "react/display-name": "off" 10 | }, 11 | "settings": { 12 | "react": { 13 | "version": "detect" 14 | } 15 | }, 16 | "globals": { "FormData": true } 17 | } 18 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # npm 2 | node_modules/ 3 | yarn-error.log 4 | 5 | # build 6 | dist/ 7 | .nyc_output/ 8 | example/js/build.js 9 | -------------------------------------------------------------------------------- /.npmignore: -------------------------------------------------------------------------------- 1 | .history/ 2 | .nyc_output/ 3 | example/ 4 | media/ 5 | tests/ 6 | helpers/ 7 | dist/example/ 8 | 9 | .travis.yml 10 | .babelrc 11 | .eslintignore 12 | .eslintrc 13 | .prettierignore 14 | .prettierrc.json 15 | ava.config.js 16 | rollup.config.js 17 | yarn-error.log 18 | -------------------------------------------------------------------------------- /.prettierignore: -------------------------------------------------------------------------------- 1 | .history/ 2 | .nyc_output/ 3 | dist/ 4 | example/js/build.js 5 | -------------------------------------------------------------------------------- /.prettierrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "tabWidth": 4, 3 | "printWidth": 100, 4 | "singleQuote": true, 5 | "trailingComma": "all" 6 | } 7 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: node_js 2 | node_js: stable 3 | script: 4 | - yarn 5 | - yarn test 6 | - yarn coverage 7 | - yarn build 8 | 9 | addons: 10 | chrome: stable 11 | 12 | deploy: 13 | provider: heroku 14 | api_key: 15 | secure: GngOWXaxIreuywPA/NJk7+YtD1Prev7QVhYGK/dIvZVbtoJWt34ywfR0zT4qybKc+NON/c79x5gc+nOfQiU83Ft6WYSPKYYolAg/VeSrKuo92sWUz8JxYtUDyMkYxZs1JgzKaKedSDLtTgENmlSuSSi7bMw001xrxzcplENGvnlrw8viMtpE1vPZ9Z1W0JV+byAWkXMLNNe/qNVkljGmil1fZK2naXGGtjQLgMVpYRNO/zieTtbK3FFXKrKN+wFnkWej6fIjFEMXvL8unKpVBcKor8hS4dqyq3Pdef6clP7jspWy4YIK9Y2NZbQffCB1vHnfdaME6cdSHmLOhi+3RJNykl01oPucDP7zq5VfZJnUn3sgaKcP8UZNgYjWg1ZrvYSDCNpnOHLtWG1BnuziHF8vnmsidmlJGK9yrH1xbSkMjMYeTPNqRjq2KbsYWgzOcl2tL6OVr7bxTGTeO9l8ERLK2IkIAmK9gtaHsEwk7tj6uhICEkvz9MuPAlVDEFsuJPQkK6X6bpaMKX/4+GqwC5Bv+r14uUMWIyPLdbgFSukx7kRh7ibJPHbnuJNrN5G0IWjPhTVc/n3pu6Uu1mzrd1aq9lMQqY0/jGQbupPWV3UnvKvU/JCl9nDQ51BOtDJcB2KeGz5I7bQ3V3WXzRbEIiL3GruBhFkR9WwKgrN2xZs= 16 | app: formv 17 | on: 18 | repo: Wildhoney/Formv 19 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2019 Adam Timberlake 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Formv 2 | 3 | > 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. 4 | 5 | ![Travis](http://img.shields.io/travis/Wildhoney/Formv.svg?style=for-the-badge) 6 |   7 | ![npm](http://img.shields.io/npm/v/formv.svg?style=for-the-badge) 8 |   9 | ![License MIT](http://img.shields.io/badge/license-mit-lightgrey.svg?style=for-the-badge) 10 |   11 | ![Coveralls](https://img.shields.io/coveralls/Wildhoney/Formv.svg?style=for-the-badge) 12 |   13 | [![code style: prettier](https://img.shields.io/badge/code_style-prettier-ff69b4.svg?style=for-the-badge)](https://github.com/prettier/prettier) 14 | 15 | --- 16 | 17 | ## Contents 18 | 19 | 1. [Getting Started](#getting-started) 20 | 2. [Customising Messages](#customising-messages) 21 | 3. [Skipping Validation](#skipping-validation) 22 | 4. [JS Validation](#js-validation) 23 | 5. [API Validation](#api-validation) 24 | 6. [Success Messages](#success-messages) 25 | 7. [Managing State](#managing-state) 26 | 8. [Form Architecture](#form-architecture) 27 | 28 | ## Getting Started 29 | 30 | Formv utilises the native [form validation](https://developer.mozilla.org/en-US/docs/Learn/HTML/Forms/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... 31 | 32 | 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`. 33 | 34 | 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. 35 | 36 | 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. 37 | 38 | ```jsx 39 | import { Form, Messages } from 'formv'; 40 | 41 | export default function MyForm() { 42 | return ( 43 |
44 | {({ isDirty, isSubmitting, feedback }) => ( 45 | <> 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 61 | 62 | )} 63 | 64 | ); 65 | } 66 | ``` 67 | 68 | **Note:** `isDirty` is an opt-in with the `withDirtyCheck` prop as it causes form data comparisons upon form change. 69 | 70 | 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. 71 | 72 | ## Customising Messages 73 | 74 | 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](https://developer.mozilla.org/en-US/docs/Web/API/ValidityState). By using the `messages` prop we can provide consistent messages across all browsers. 75 | 76 | ```jsx 77 | import { Form, Messages } from 'formv'; 78 | 79 | const messages = { 80 | name: { valueMissing: 'Please enter your first and last name.' }, 81 | email: { 82 | valueMissing: 'Please enter your email address.', 83 | typeMismatch: 'Please enter a valid email address.', 84 | }, 85 | age: { 86 | valueMissing: 'Please enter your age.', 87 | rangeUnderflow: 'You must be 18 or over to use this form.', 88 | }, 89 | }; 90 | 91 |
; 92 | ``` 93 | 94 | 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. 95 | 96 | ## Skipping Validation 97 | 98 | 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](https://www.w3schools.com/jsref/prop_form_novalidate.asp). 99 | 100 | 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. 101 | 102 | ```jsx 103 | 104 | 105 | ``` 106 | 107 | 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. 108 | 109 | ## JS Validation 110 | 111 | For the most part the native HTML validation is sufficient for our forms, especially when you consider the power that the [`pattern` attribute](https://www.w3schools.com/tags/att_input_pattern.asp) 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. 112 | 113 | ```jsx 114 | import { Form, Error } from 'formv'; 115 | import * as utils from './utils'; 116 | 117 | const handleSubmitting = () => { 118 | 119 | if (!utils.passesQuirkyValidation(state)) { 120 | throw new Error.Validation({ 121 | name: 'Does not pass our quirky validation rules.' 122 | }); 123 | } 124 | 125 | }); 126 | 127 | 128 | ``` 129 | 130 | It's worth noting that any errors that are thrown from the `onSubmitting` handler will be merged with the native HTML validation messages. 131 | 132 | ## API Validation 133 | 134 | 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. 135 | 136 | 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`. 137 | 138 | Continuing from the above example, we'll implement the `handleSubmitted` function which handles the submitting of the data to the API. 139 | 140 | ```jsx 141 | import { Form, Error } from 'formv'; 142 | 143 | async function handleSubmitted() { 144 | try { 145 | await api.post('/send', data); 146 | } catch (error) { 147 | const isBadRequest = error.response.status === 400; 148 | if (isBadRequest) throw new Error.Validation(error.response.data); 149 | throw error; 150 | } 151 | } 152 | 153 | ; 154 | ``` 155 | 156 | 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. 157 | 158 | ```javascript 159 | throw new Error.Validation({ 160 | name: 'Please enter your first and last name.', 161 | age: 'You must be 18 or over to use this form.', 162 | }); 163 | ``` 164 | 165 | 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. 166 | 167 | ```jsx 168 | import { Form, Error } from 'formv'; 169 | 170 | async function handleSubmitted() { 171 | try { 172 | await api.post('/send', data); 173 | } catch (error) { 174 | const isBadRequest = error.response.status === 400; 175 | const isAxiosError = error.isAxiosError; 176 | 177 | if (isBadRequest) throw new Error.Validation(error.response.data); 178 | if (isAxiosError) throw new Error.Generic(error.response.data); 179 | throw error; 180 | } 181 | } 182 | 183 | ; 184 | ``` 185 | 186 | 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. 187 | 188 | ## Success Messages 189 | 190 | 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. 191 | 192 | ```jsx 193 | import { Form, Success, Error } from 'formv'; 194 | 195 | async function handleSubmitted() { 196 | try { 197 | await api.post('/send', data); 198 | return new Success('Everything went swimmingly!'); 199 | } catch (error) { 200 | const isBadRequest = error.response.status === 400; 201 | const isAxiosError = error.isAxiosError; 202 | 203 | if (isBadRequest) throw new Error.Validation(error.response.data); 204 | if (isAxiosError) throw new Error.Generic(error.response.data); 205 | throw error; 206 | } 207 | } 208 | 209 | ; 210 | ``` 211 | 212 | ## Managing State 213 | 214 | 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](https://github.com/streamich/react-use/blob/master/docs/useMap.md) with a handful of differences – currying, memoization and nested properties. 215 | 216 | ```javascript 217 | import { useMap } from 'formv'; 218 | 219 | const [state, { set }] = useMap({ 220 | username: null, 221 | profile: { 222 | age: null, 223 | created: null, 224 | }, 225 | }); 226 | ``` 227 | 228 | 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`](https://reactjs.org/docs/react-api.html#reactmemo). 229 | 230 | ```jsx 231 | 232 | 233 | 234 | ``` 235 | 236 | 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. 237 | 238 | ```jsx 239 | set('username', target.value)} /> 240 | ``` 241 | 242 | You'll also notice that nested objects are handled with the dot notation thanks to [`Lodash`](https://lodash.com/). 243 | 244 | ## Form Architecture 245 | 246 | 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. 247 | 248 | 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. 249 | 250 | Using `Formv` it's easy to have the aforementioned setup as illustrated below. 251 | 252 | ```jsx 253 | import * as fv from 'formv'; 254 | 255 | function Form() { 256 | const [state, { set }] = fv.useMap({ 257 | name: null, 258 | age: null, 259 | }); 260 | 261 | return ( 262 | 263 | {({ feedback }) => ( 264 | <> 265 | 266 | 267 | 268 |
269 | 270 | )} 271 | 272 | ); 273 | } 274 | ``` 275 | 276 | ```jsx 277 | function Fieldset({ onChange }) { 278 | return ( 279 | <> 280 | 281 | 282 | 283 | ); 284 | } 285 | ``` 286 | 287 | ```jsx 288 | import * as fv from 'formv'; 289 | 290 | function FieldName({ onChange }) { 291 | const { feedback } = fv.useState(); 292 | 293 | return ( 294 | <> 295 | onChange(target.value)} /> 296 | 297 | 298 | ); 299 | } 300 | ``` 301 | 302 | ```jsx 303 | import * as fv from 'formv'; 304 | 305 | function FieldAge({ onChange }) { 306 | const { feedback } = fv.useState(); 307 | 308 | return ( 309 | <> 310 | onChange(target.value)} /> 311 | 312 | 313 | ); 314 | } 315 | ``` 316 | -------------------------------------------------------------------------------- /ava.config.js: -------------------------------------------------------------------------------- 1 | export default { 2 | failFast: true, 3 | require: [ 4 | '@babel/register', 5 | '@babel/polyfill', 6 | './helpers/enzyme.js', 7 | './helpers/browser-env.js', 8 | ], 9 | }; 10 | -------------------------------------------------------------------------------- /example/.babelrc: -------------------------------------------------------------------------------- 1 | { "presets": ["@babel/preset-env", "@babel/preset-react"] } 2 | -------------------------------------------------------------------------------- /example/images/information.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 5 | 6 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | -------------------------------------------------------------------------------- /example/images/logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Wildhoney/Formv/b2d4946346f33c3b4cea62117767f26cb6934b06/example/images/logo.png -------------------------------------------------------------------------------- /example/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | Formv Example 8 | 9 | 13 | 14 | 15 |
16 | 17 | 67 | 68 | 69 | -------------------------------------------------------------------------------- /example/js/components/Field/index.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import PropTypes from 'prop-types'; 3 | import * as fv from 'formv'; 4 | import * as e from './styles'; 5 | 6 | export default function Field({ children, ...props }) { 7 | return ( 8 | 9 | {children} 10 | 11 | ); 12 | } 13 | 14 | Field.propTypes = { children: PropTypes.node.isRequired }; 15 | -------------------------------------------------------------------------------- /example/js/components/Field/styles.js: -------------------------------------------------------------------------------- 1 | import styled from 'styled-components'; 2 | 3 | export const Container = styled.div` 4 | display: grid; 5 | grid-auto-flow: row; 6 | border: 1px solid lightgray; 7 | `; 8 | -------------------------------------------------------------------------------- /example/js/components/Form/index.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import PropTypes from 'prop-types'; 3 | import * as fv from 'formv'; 4 | import Input from '../Input'; 5 | import Textarea from '../Textarea'; 6 | import Field from '../Field'; 7 | import Messages from '../Messages'; 8 | import * as e from './styles'; 9 | import * as utils from './utils'; 10 | 11 | export default function Form({ ...props }) { 12 | const [state, { set, reset }] = fv.useMap({ 13 | name: '', 14 | email: '', 15 | message: '', 16 | }); 17 | 18 | return ( 19 | 25 | {({ isSubmitting, feedback }) => ( 26 | <> 27 | 28 | 29 | 30 | 31 | 32 | 33 | 42 | 43 | 44 | 45 | 46 | 55 | 56 | 57 | 58 | 59 |