Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/jalik/js-form-parser
A utility to parse complex forms with minimum effort.
https://github.com/jalik/js-form-parser
form parser
Last synced: 3 months ago
JSON representation
A utility to parse complex forms with minimum effort.
- Host: GitHub
- URL: https://github.com/jalik/js-form-parser
- Owner: jalik
- License: mit
- Created: 2017-11-14T07:01:51.000Z (about 7 years ago)
- Default Branch: main
- Last Pushed: 2024-04-29T23:36:45.000Z (9 months ago)
- Last Synced: 2024-10-15T03:47:20.766Z (4 months ago)
- Topics: form, parser
- Language: TypeScript
- Homepage:
- Size: 2.32 MB
- Stars: 8
- Watchers: 3
- Forks: 1
- Open Issues: 3
-
Metadata Files:
- Readme: README.md
- Changelog: CHANGELOG.md
- Contributing: CONTRIBUTING.md
- License: LICENSE.txt
Awesome Lists containing this project
README
# @jalik/form-parser
![GitHub package.json version](https://img.shields.io/github/package-json/v/jalik/js-form-parser.svg)
![Build Status](https://github.com/jalik/js-form-parser/actions/workflows/node.js.yml/badge.svg)
![Last commit](https://img.shields.io/github/last-commit/jalik/js-form-parser.svg)
[![GitHub issues](https://img.shields.io/github/issues/jalik/js-form-parser.svg)](https://github.com/jalik/js-form-parser/issues)
![GitHub](https://img.shields.io/github/license/jalik/js-form-parser.svg)
![npm](https://img.shields.io/npm/dt/@jalik/form-parser.svg)## Features
- Collect and parse form values in one line
- Parse values based on field type (ex: `type="number"`) or data-type (ex: `data-type="boolean"`)
- Use custom parser with `data-type`
- Build arrays and objects based on field name
- Trim and nullify values
- Filter values using a custom function
- Clean values using a custom function
- Framework-agnostic
- TypeScript declarations ♥## Sandbox
Play with the lib here: https://codesandbox.io/s/jalik-form-parser-demo-r29grh?file=/src/index.js
## Installing
```shell
npm i -P @jalik/form-parser
```
```shell
yarn add @jalik/form-parser
```## Getting started
Let's start with the form below :
```html
Submit```
You can collect and parse fields with `parseForm(form, options)`.
```js
import { parseForm } from '@jalik/form-parser'// Get an existing HTML form element
const form = document.getElementById('my-form')// Parse form values with default options
const fields = parseForm(form)
```The `fields` object will look like this :
```json
{
"username": "jalik",
"password": "secret",
"age": 35,
"gender": "male",
"email": "[email protected]",
"phone": "067123456",
"subscribe": true,
"token": "aZ7hYkl12mPx"
}
```Below is a more complete form example, with a lot of different cases to help you understand the
behavior of the parsing function (pay attention to comments, values and attributes).```html
10
20
30
Hello
10
20
30
```
To get form fields :
```js
import { parseForm } from '@jalik/form-parser'// Get an existing HTML form element
const form = document.getElementById('my-form')// Parse form values using default options
const fields = parseForm(form)
```The `fields` object will look like this :
```json
{
"boolean": false,
"hidden_boolean": true,
"float": 9.99,
"hidden_float": 9.99,
"text_integer": 1,
"integer": 1,
"range": 118,
"select_number": 30,
"date": "2017-11-14",
"file": "file://path/to/file.txt",
"hidden_text": "shadowed",
"month": "2017-11",
"number_text": "0123",
"text": "Hello",
"url": "http://www.github.com/",
"textarea": "Hello",
"password": " 1337 ",
"array": [
"A",
"B"
],
"select_multiple": [
20,
30
]
}
```## Building arrays
To get an array of values, append `[]` to a field name:
```html
```Get fields values :
```js
import { parseForm } from '@jalik/form-parser'// Get an existing HTML form element
const form = document.getElementById('my-form')// Parse form values using default options
const fields = parseForm(form)
```The `fields` object will look like this :
```json
{
"array": [
"B",
"C"
],
"colors": [
"white",
undefined,
"red"
]
}
```## Building objects
To get an object, write attributes like `[attribute]`:
```html
```Get fields values :
```js
import { parseForm } from '@jalik/form-parser'// Get an existing HTML form element
const form = document.getElementById('my-form')// Parse form values using default options
const fields = parseForm(form)
```The `fields` object will look like this :
```json
{
"address": {
"street": "Av. Pouvanaa a Oopa",
"city": "Papeete"
}
}
```### Using numbers as keys in objects (since v2.0.6)
If you need to create an object with numbers as attributes, use single or double quotes to force the
parser to interpret it as a string and then creating an object instead of an array.```html
```Will give this :
```json
{
"elements": {
"0": "Zero",
"1": "One",
"2": "Two"
}
}
```Instead of :
```json
{
"elements": [
"Zero",
"One",
"Two"
]
}
```## Parsing fields
To define the type of field, you can use the attribute `data-type` or `type`.
The attribute `data-type` takes precedence over `type` if both of are defined.When using `data-type` attribute, the value can be:
* `auto` to convert the value to the best guess type (ex: `123` => `number`, `true` => `boolean`)
* `boolean` to convert the value to a boolean (ex: `true`, `1`, `yes`, `on`, `false`, `0`, `no`, `off`)
* `number` to convert the value to a numberWhen using `type` attribute on ``, only `number` and `range` are parsed to numbers.
```html
```
## Using a custom parser
You may want to create your own `data-type`, it is possible since the `v3.1.0` by passing the `parser` option to `parseForm()` or `parseField()`.
```html
```
```js
import { parseForm } from '@jalik/form-parser'const form = document.getElementById('my-form')
const fields = parseForm(form, {
parser: (value, dataType, field) => {
if (dataType === 'phone') {
const [code, number] = value.split(/\./)
return {
code,
number,
}
}
return null
},
})
``````json
{
"phone": {
"code": "689",
"number": "12345678"
}
}
```## Parsing complex forms with nested fields
It is possible to reconstruct an object corresponding to the form structure, so it can
parse complex forms containing nested arrays and objects.```html
```To get fields :
```js
import { parseForm } from '@jalik/form-parser'// Get an existing HTML form element
const form = document.getElementById('my-form')// Parse form values using default options
const fields = parseForm(form)
```The `fields` object will look like this :
```json
{
"phones": [
{
"code": "689",
"number": "87218910"
},
{
"code": "689",
"number": "87218910"
}
],
"deep_1": [
{
"deep_2": [
[
{
"deep_3": "DEEP"
}
]
]
}
]
}
```## Filtering
When parsing a form, you can filter values with `filterFunction(field, parsedValue)` option in the `parseForm(form, options)`.
The filter function must return `true` to return the field.```js
import { parseForm } from '@jalik/form-parser'// Get an existing HTML form element
const form = document.getElementById('my-form')const fields = parseForm(form, {
// returns only text fields
filterFunction: (field, parsedValue) => field.type === 'text'
});
```## Cleaning
Values can be cleaned by passing `cleanFunction(value, field)` to `parseForm(form, options)`.
Note that only strings are passed to this function and that password fields are ignored.```js
import { parseForm } from '@jalik/form-parser'// Get an existing HTML form element
const form = document.getElementById('my-form')// Parse form values using default options
const fields = parseForm(form, {
cleanFunction: (value, field) => {
// Apply uppercase to lastName field
if (field.name === 'lastName' || /name/gi.test(field.name)) {
value = value.toUpperCase()
}
// Remove HTML code from all fields
return value.replace(/<\/?[^>]+>/gm, '')
}
})
```## API
### parseField(field, options)
To parse a single field.
```html
1
2
3
```
```js
import { parseField } from '@jalik/form-parser'const field = document.getElementById('values')
const values = parseField(field)
// values = [2, 3]
```### parseForm(form, options)
To parse a form with all fields.
```html
1
2
3
```
```js
import { parseForm } from '@jalik/form-parser'// Get an existing HTML form element
const form = document.getElementById('my-form')const fields = parseForm(form, {
// Cleans parsed values
cleanFunction(value, field) {
return typeof value === 'string' ? stripTags(value) : value
},
// Only returns fields that matches the condition
filterFunction(field) {
return field.type === 'text'
},
// Replace empty strings with null
nullify: true,
// Set parsing mode.
// - none: disable parsing
// - type: enable parsing based on "type" attribute (ex: type="number")
// - data-type: enable parsing based on "data-type" attribute (ex: data-type="number")
// - auto: enable parsing based on data-type and type (in this order)
parsing: 'none' | 'type' | 'data-type' | 'auto',
// Remove extra spaces
trim: true
})
```## Changelog
History of releases is in the [changelog](./CHANGELOG.md).
## License
The code is released under the [MIT License](http://www.opensource.org/licenses/MIT).