npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

x-form-lib

v0.0.11

Published

A customizable form library for building dynamic forms with validation, event handling, and error management.

Downloads

546

Readme

XFormLib

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.

Demo

Features

  • One library that handles complete form submission paths.
  • All resources included in a single CDN (both styles and code).
  • Prevents style conflicts by using recompiled inputtel elements with custom classes.
  • Low bundle size
  • Distributed in 2 version - IIFE modules and EcmaScript modules;
  • Default validation for common input types
  • Highly customizable
  • Default form submit handler with support of facebook pixel lead send
  • Can send form data in 2 format

Browser Compatibility

| 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.

Getting Started (Using a CDN)

  1. Add the plugin script and initialise it on your container
<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>

Getting Started npm package

  1. Install with npm: npm install x-form-lib --save or yarn: yarn add x-form-lib

  2. 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 Class

The 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.

Constructor Parameters

  • 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".

Example Usage CDN

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();

Example Usage npm package

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();

Methods

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.

  • Parameters:
    • 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 Class

The 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.

Constructor Parameters

  • 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.

Methods

  • render()
    Renders the input element along with its wrapper and error message elements. The method returns the wrapper element, which contains the input and error message.

Example Usage CDN

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"),
});

Example Usage npm package

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"),
});

Notes

  • The 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.
  • Custom validation functions can be provided, or the class will attempt to use default validation functions for common input names like firstName, lastName, and email.
  • Error messages can be customized and are only displayed if isNeedErrorMessage is set to true.
  • The class supports callback functions for onChange, onFocus, and onBlur events, allowing for additional behavior to be triggered during user interactions.

PhoneInput Class

The PhoneInput class extends the Input class to provide additional functionality for handling phone number inputs with international support.

Constructor Parameters

  • 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.

Methods

  • 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.

Example Usage CDN

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());

Example Usage npm package

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());

Notes

  • The PhoneInput class adds support for international phone number formatting and validation using the intl-tel-input library.
  • The 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.
  • If a validationFunc is not provided, the class uses the default validation function provided by the intl-tel-input library.
  • Error handling and validation are customizable through the various parameters.

Handle Facebook pixel

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.

Contributing

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.