voc-lib-js
v1.0.67
Published
A JavaScript library for VocPhone
Maintainers
Readme
Vocphone JavaScript Library
Lightweight form rendering and submission helper for VocPhone projects. This library renders JSON-driven forms into the DOM, collects values (FormData or plain objects), and supports auto-submit to an API endpoint.
Quick start
Install dependencies and build (if developing locally):
npm install
npm run buildInclude the bundle from a CDN (UMD/global) or import as a module in your app.
CDN usage
CommonJS (global UMD bundle):
<div id="render-form"></div>
<script src="https://cdn.jsdelivr.net/npm/voc-lib-js@latest/dist/main.global.js"></script>
<script>
// global namespace is `VocLibJs` (example)
const rendered = VocLibJs.FormsLib.renderForm('#render-form', formSchema);
rendered.onSubmit((data) => {
// `data` is a FormData by default
console.log([...data.entries()]);
});
</script>ES Module (module bundle):
<div id="render-form"></div>
<script type="module">
import { FormsLib } from 'https://cdn.jsdelivr.net/npm/voc-lib-js@latest/dist/main.mjs';
const rendered = FormsLib.renderForm('#render-form', formSchema);
// use rendered as needed
console.log(rendered.getValues(false)); // plain object
</script>NPM / Framework usage
Install:
npm install voc-lib-jsExample using Vue (works the same in React, Angular, Svelte, or vanilla JS):
<script setup>
import { onMounted, ref } from 'vue';
import { FormsLib } from 'voc-lib-js';
const formRef = ref(null);
onMounted(() => {
formRef.value = FormsLib.renderForm('#render-form', formSchema);
console.log('Initial values (object):', formRef.value.getValues(false));
});
</script>
<template>
<div id="render-form"></div>
</template>API Reference
Main function
renderForm(element, data, options?) => RenderedForm | null
- element: CSS selector string or HTMLElement
- data: form schema object (see 'Form schema' below)
- options: optional object
- onSubmit?: callback when auto-submit used
- onSubmitResult?: callback that receives (response, error) when submitConfig is used
- enableAutoSubmit?: boolean
- style?: "bootstrap" — add Bootstrap classes to inputs
- submit_config?: SubmitConfig — alternative place to pass submit configuration
RenderedForm (returned object)
- element: HTMLFormElement — the generated form element
- validate(): returns Array<{ element: HTMLElement, message: string }> — list of invalid fields and messages
- getValues(asFormData = true): FormData | Record<string, any> — read form values. Default returns FormData. Pass false to get a plain object.
- onSubmit(callback): attach a submit listener that receives (data, event)
SubmitConfig
- url: string — endpoint to post to
- api_token?: string — optional Authorization token
- additional_data?: Record<string, any> — merged into payload
Form schema
Top-level form object (Type: FormData in source)
- id: string — unique id for the form element
- code: string — optional code reference
- form_name: string — title displayed as an H2 inside the form
- default_values?: object — map of field name -> default value
- submit_config?: SubmitConfig — server submit configuration (optional)
- fields: array — list of Field objects (see below)
Field (BaseField)
- label?: string — visible label
- key: string — name for the input (used as name/id). If you need a different name, use
name. - name?: string — alternative to
key(backwards compatibility) - type?: string — one of: text, email, password, textarea, radio, select, checkbox, file, row
- placeholder?: string
- required?: boolean
- validation?: { min_length?: number, max_length?: number, regex?: string }
- hint_text?: string — small helper text below input
- direction?: 'horizontal' | 'vertical' — for radio/checkbox/row
- options?: [{ label, value }] — for radio/select/checkbox groups
- default?: string — default value for the field
- width?: string — CSS width (e.g. '100px', '50%')
- accept?: string — for file inputs (e.g. 'image/*')
- multiple?: boolean — for file inputs or multi-value fields
RowField (type: 'row') — contains items: BaseField[] and renders them horizontally by default.
Example form schemas
- Simple registration form
{
"id": "user-registration",
"code": "reg_001",
"form_name": "User Registration",
"default_values": {
"country": "usa"
},
"fields": [
{ "label": "First name", "key": "first_name", "type": "text", "required": true },
{ "label": "Last name", "key": "last_name", "type": "text", "required": true },
{ "label": "Email", "key": "email", "type": "email", "required": true },
{ "label": "Password", "key": "password", "type": "password", "required": true },
{
"label": "Country",
"key": "country",
"type": "select",
"options": [
{ "label": "United States", "value": "usa" },
{ "label": "Canada", "value": "canada" }
]
}
]
}- Complex form: row, radio, checkbox, file
{
"id": "survey-1",
"form_name": "Survey",
"fields": [
{
"type": "row",
"label": "Personal info",
"items": [
{ "label": "First name", "key": "first_name", "type": "text" },
{ "label": "Last name", "key": "last_name", "type": "text" }
]
},
{
"label": "Gender",
"key": "gender",
"type": "radio",
"options": [
{ "label": "Male", "value": "male" },
{ "label": "Female", "value": "female" }
],
"direction": "horizontal"
},
{
"label": "Hobbies",
"key": "hobbies",
"type": "checkbox",
"options": [
{ "label": "Sports", "value": "sports" },
{ "label": "Music", "value": "music" }
]
},
{
"label": "Upload resume",
"key": "resume",
"type": "file",
"accept": ".pdf,.doc,.docx"
}
]
}Handling values and submission
Use getValues() to retrieve form values. By default it returns a FormData instance which is ideal for file uploads. Pass false to get a plain object where repeated keys become arrays.
Example reading values:
const rendered = FormsLib.renderForm('#render-form', formSchema);
// FormData (default)
const data = rendered.getValues();
console.log(data.get('email'));
// Plain object
const obj = rendered.getValues(false);
console.log(obj);
// Attach submit handler
rendered.onSubmit((data, event) => {
// If auto-submit isn't enabled, you can manually POST `data` using fetch.
console.log(data);
});Auto-submit
If the schema includes submit_config or you pass submit_config in options, the library will intercept the form submit and call the internal submit helper which posts to the configured endpoint. You can pass onSubmitResult in options to receive (response, error).
Example submit_config on the schema:
{
"submit_config": {
"url": "https://api.example.com/forms/submit",
"api_token": "<token>",
"additional_data": { "source": "website" }
},
"fields": [
...
]
}Developer notes / edge cases
- File inputs cannot be programmatically pre-filled for security reasons. Use
default_valuesto display a filename elsewhere if needed. - Validation:
validation.min_lengthandvalidation.max_lengthmap to elementminLengthandmaxLength.validation.regexmaps topatternfor inputs; for textareas it's stored indata-pattern. - For checkbox groups,
getValues(false)will return arrays when multiple options are checked.
Contributing
- Fork the repo and create a feature branch.
- Run
npm installandnpm run buildto test locally. - Open a PR with a clear description and include tests for new behavior where appropriate.
License
MIT
