
Security News
Axios Supply Chain Attack Reaches OpenAI macOS Signing Pipeline, Forces Certificate Rotation
OpenAI rotated macOS signing certificates after a malicious Axios package reached its CI pipeline in a broader software supply chain attack.
x-form-lib
Advanced tools
A customizable form library for building dynamic forms with validation, event handling, and error management.
This package is an out-of-the-box solution for form creation and submission. You don’t need to install an HTML template for the form, worry about validation, connect third-party libraries, and so on—XFormLib takes care of all of that for you. You can fully customize the form and its content using hooks like onSubmit, onError, and onSuccess. Additionally, you can pass any HTML attributes to the form or input, modify validation, and adjust classes as needed, or setup your custom validation.
Under the hood, this library uses intl-input-phone for phone number input validation. You can pass any props to it, and if your site already has styles for intl-input-phone, there’s no problem—XFormLib uses a custom build of intl-input-phone where all classes have a prefix different from intl, so you don’t have to worry about style conflicts.
Additionally, this package provides a modal window that displays after the form submission result. You can also customize this behavior to suit your needs.
| Chrome | Firefox | Safari | Edge |
|---|---|---|---|
| ✓ | ✓ | ✓ | ✓ |
Note: We have now dropped support for all versions of Internet Explorer because it is no longer supported by any version of Windows.
<div id="my-form-container"></div>
<script src="https://cdn.jsdelivr.net/npm/x-form-lib@latest/dist/index.js"></script>
<script>
const form = new XFormLib.Form({
containerSelector: "#my-form-container",
url: "https://some-server/",
});
form.render();
</script>
Install with npm: npm install x-form-lib --save or yarn: yarn add x-form-lib
Import the JS and initialise the plugin on your input element
import { Form } from "x-form-lib";
const form = new Form({ containerSelector: "#myFormContainer" });
form.render();
When you initialize the form, you must provide an options object. In this object, only two field is required: containerSelector, url which indicates the container to which the form will be appended, and url on wich form data will send using POST method. The default form contains four fields: email, phone, firstName, and lastName. It uses default validation functions and style classes, but you can override them. Below, you can see a full description of the parameters.
url
Type: String Required
This parameter specifies the URL to which the form data will be sent upon submission.
containerSelector
Type: String | Array<string> Required
This parameter is used to select the container in which the form will be rendered. It is a required parameter. If the selector is invalid, an error will be thrown. If you need to render the form in two or more places, use an array of selectors.
defaultValues
Type: Array<{name: string, value: string}> Default: []
This acts as an analog of hidden fields, appending values to the form payload when it is sent to the target URL. Exaple:
const defaultValues = [
{ name: "custom1", value: "123" },
{ name: "custom2", value: "rtg" },
];
elements
Type: Array<Input> Default:
[
new Input({ type: "text", name: "firstName" }),
new Input({ type: "text", name: "lastName" }),
new Input({ type: "text", name: "email" }),
new PhoneInput({ name: "phone" }),
];
Form ClassThe Form class is a customizable form builder designed to simplify the creation, rendering, and submission of forms with built-in validation, event handling, and error management. It allows developers to create dynamic forms with ease, while providing flexibility in styling and behavior.
url (Required)
Type: String
The endpoint to which the form data will be submitted. This must be a valid URL.
containerSelector (Required)
Type: String
The CSS selector for the container in which the form will be rendered. The selector must point to an existing DOM element.
defaultValues
Type: Array<Object>
Default: []
An array of default values to populate the form fields. Essentially, this serves as a replacement for hidden inputs. The origin property can be "URL" if the value should be retrieved from the URL query parameters.
elements
Type: Array<Object>
Default:
[
new Input({ type: "text", name: "firstName" }),
new Input({ type: "text", name: "lastName" }),
new Input({ type: "text", name: "email" }),
new PhoneInput({ name: "phone" }),
];
An array of custom elements to include in the form. If not provided, default elements (firstName, lastName, email, phone) will be used.
submitBtnClass
Type: String
Default: "dALzpi__SubmitButton"
The CSS class to apply to the submit button.
submitBtnWrapperClass
Type: String
Default: "dALzpi__submitBtnWrapperClass"
The CSS class to apply to the wrapper around the submit button.
submitBtnAttributes
Type: Array<Object>
Default: []
Additional attributes for the submit button. Each attribute is an object with name and value properties.
onSubmit
Type: Function
Default: null
A custom function to execute on form submission. If not provided, the defaultOnSubmit method will be used.
submitBtnText
Type: String
Default: "Submit"
The text to display on the submit button.
onError
Type: Function
Default: null
A custom function to handle errors during form submission.
onSuccess
Type: Function
Default: null
A custom function to handle successful form submission.
onFormValidationError
Type: Function
Default: null
A custom function to handle form validation errors.
className
Type: String
Default: ""
Additional CSS classes to apply to the form element.
formPayloadReqType
Type: String
Default: "JSON"
Defines the content type for the form data submission. Can be either "JSON" or "X_URL_FORM_ENCODED".
const { Form, Input, PhoneInput } = XFormLib;
const form = new Form({
url: "https://example.com/submit",
containerSelector: "#form-container",
elements: [
new Input({ type: "text", name: "username" }),
new Input({ type: "password", name: "password" }),
new PhoneInput({ name: "phone" }),
],
submitBtnText: "Register",
onSuccess: () => {
console.log("Form submitted successfully!");
},
onError: (error) => {
console.error("Error submitting form:", error);
},
formPayloadReqType: "X_URL_FORM_ENCODED",
});
form.render();
import { Form, Input, PhoneInput } from "x-form-lib";
const form = new Form({
url: "https://example.com/submit",
containerSelector: "#form-container",
elements: [
new Input({ type: "text", name: "username" }),
new Input({ type: "password", name: "password" }),
new PhoneInput({ name: "phone" }),
],
submitBtnText: "Register",
onSuccess: () => {
console.log("Form submitted successfully!");
},
onError: (error) => {
console.error("Error submitting form:", error);
},
formPayloadReqType: "X_URL_FORM_ENCODED",
});
form.render();
defaultOnSubmit(event)Handles the form submission event, validates the form, displays a loading indicator, and sends form data to the specified URL. Handles both success and error scenarios, and automatically redirects if an autologin URL is provided.
event (Event): The form submission event.render()Renders the form into the specified container, attaching all necessary elements, event listeners, and handling the creation of the submit button and popup component.
Input ClassThe Input class provides a flexible and customizable way to create and manage form input elements in JavaScript. It includes features such as custom attributes, validation, error handling, and event listeners for different input interactions.
type
Type: String
Default: "text"
Specifies the type of the input element, such as "text", "email", "password", etc.
name
Type: String
Required
The name attribute for the input element. It is also used as the placeholder if no placeholder is provided.
attributes
Type: Array
Default: []
A list of additional attributes to set on the input element. Each attribute should be an object with name and value properties.
validationFunc
Type: Function
Default: null
A custom validation function for the input value. If not provided, the class will try to use a default validation function based on the input name.
placeholder
Type: String
Default: name
Placeholder text for the input element. If not provided, the name is used as the placeholder.
isTouchErrorSchema
Type: Boolean
Default: true
Determines if the error schema should only be applied after the input has been touched (focused and blurred).
isNeedErrorMessage
Type: Boolean
Default: true
Indicates whether an error message should be displayed below the input element.
className
Type: String
Default: "dALzpi__input"
The CSS class name for the input element.
wrapperClassName
Type: String
Default: "dALzpi__fieldWrapper"
The CSS class name for the wrapper element that contains the input and error message elements.
errorClassName
Type: String
Default: "dALzpi__fieldError"
The CSS class name applied to the input element when there is a validation error.
errorMessageClassName
Type: String
Default: "dALzpi__errorMessage"
The CSS class name for the error message element.
onChange
Type: Function
Optional
A callback function triggered on the input event.
onFocus
Type: Function
Optional
A callback function triggered on the focus event.
onBlur
Type: Function
Optional
A callback function triggered on the blur event.
render()const { Input } = XFormLib;
const input = new Input({
name: "email",
type: "email",
placeholder: "Enter your email",
validationFunc: (value) => {
const emailRegex = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/;
return emailRegex.test(value) ? null : "Invalid email address";
},
className: "email-input",
wrapperClassName: "email-input-wrapper",
errorClassName: "email-input-error",
errorMessageClassName: "email-input-error-message",
onChange: (event) => console.log("Input changed:", event.target.value),
onFocus: () => console.log("Input focused"),
onBlur: () => console.log("Input blurred"),
});
import { Input } from "x-form-lib";
const input = new Input({
name: "email",
type: "email",
placeholder: "Enter your email",
validationFunc: (value) => {
const emailRegex = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/;
return emailRegex.test(value) ? null : "Invalid email address";
},
className: "email-input",
wrapperClassName: "email-input-wrapper",
errorClassName: "email-input-error",
errorMessageClassName: "email-input-error-message",
onChange: (event) => console.log("Input changed:", event.target.value),
onFocus: () => console.log("Input focused"),
onBlur: () => console.log("Input blurred"),
});
Input class is designed to be flexible, allowing you to pass in a variety of options to customize the input element to meet your needs.firstName, lastName, and email.isNeedErrorMessage is set to true.onChange, onFocus, and onBlur events, allowing for additional behavior to be triggered during user interactions.PhoneInput ClassThe PhoneInput class extends the Input class to provide additional functionality for handling phone number inputs with international support.
intlOptions
Type: Object
Default: {}
Options for international telephone input. This object can include configuration options for the international phone input library. It can also specify a geoIpLookup function to determine the user's country based on their IP address. It support all options from intl-tel-input
inputOptions
Type: Object
Additional options for the Input class. These are passed through to the parent Input class and include parameters such as type, name, attributes, validationFunc, placeholder, isTouchErrorSchema, isNeedErrorMessage, className, wrapperClassName, errorClassName, errorMessageClassName, onChange, onFocus, and onBlur.
initIntl()
Initializes the international telephone input library with the provided options and a default geo IP lookup function if none is provided.
#getErrorMessage(errorCode)
Type: Function
Returns the error message corresponding to a given phone validation error code.
_getDefaultValidationFunction()
Type: Function
Returns a validation function that uses the international telephone input library to validate the phone number.
const { PhoneInput } = XFormLib;
const phoneInput = new PhoneInput({
name: "phone",
intlOptions: {
geoIpLookup: (success, failure) => {
fetch("https://ipapi.co/json")
.then((res) => res.json())
.then((data) => success(data.country_code))
.catch(() => failure());
},
initialCountry: "us",
},
placeholder: "Enter your phone number",
className: "phone-input",
wrapperClassName: "phone-input-wrapper",
errorClassName: "phone-input-error",
errorMessageClassName: "phone-input-error-message",
onChange: (event) => console.log("Phone input changed:", event.target.value),
onFocus: () => console.log("Phone input focused"),
onBlur: () => console.log("Phone input blurred"),
});
phoneInput.initIntl();
document.body.appendChild(phoneInput.render());
import { PhoneInput } from "x-form-lib";
const phoneInput = new PhoneInput({
name: "phone",
intlOptions: {
geoIpLookup: (success, failure) => {
fetch("https://ipapi.co/json")
.then((res) => res.json())
.then((data) => success(data.country_code))
.catch(() => failure());
},
initialCountry: "us",
},
placeholder: "Enter your phone number",
className: "phone-input",
wrapperClassName: "phone-input-wrapper",
errorClassName: "phone-input-error",
errorMessageClassName: "phone-input-error-message",
onChange: (event) => console.log("Phone input changed:", event.target.value),
onFocus: () => console.log("Phone input focused"),
onBlur: () => console.log("Phone input blurred"),
});
phoneInput.initIntl();
document.body.appendChild(phoneInput.render());
PhoneInput class adds support for international phone number formatting and validation using the intl-tel-input library.intlOptions parameter allows customization of the phone input widget, including specifying a custom geoIpLookup function to automatically set the initial country based on the user's IP address.validationFunc is not provided, the class uses the default validation function provided by the intl-tel-input library.The default onSubmit handler will send a Facebook lead if window.fbq exists and a Google Analytics lead if window.gtag exists and gl is in defaultValues.
See the contributing guide for instructions on setting up the project and making changes, and also on how to update to a new version of libphonenumber, how to update the flag images, or how to add a new translation.
FAQs
A customizable form library for building dynamic forms with validation, event handling, and error management.
The npm package x-form-lib receives a total of 2 weekly downloads. As such, x-form-lib popularity was classified as not popular.
We found that x-form-lib demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 0 open source maintainers collaborating on the project.
Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Security News
OpenAI rotated macOS signing certificates after a malicious Axios package reached its CI pipeline in a broader software supply chain attack.

Security News
Open source is under attack because of how much value it creates. It has been the foundation of every major software innovation for the last three decades. This is not the time to walk away from it.

Security News
Socket CEO Feross Aboukhadijeh breaks down how North Korea hijacked Axios and what it means for the future of software supply chain security.