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

@bepasquet/dynamic-form

v3.2.4

Published

Dynamic Forms Web Component

Downloads

17

Readme

@bepasquet/dynamic-form

Published on webcomponents.org

npm (scoped)

Dynamic form is a webcomponent that makes angular dynamic form approach available on vanilla js please feel free to open issues, sugestions and code improvements everything is welcome

Install

$ npm install @bepasquet/dynamic-form

Usage

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Test</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">

</head>
<body>
    <script src="node_modules/@bepasquet/dynamic-form/dist/index.js">

    <dynamic-form>
      <link
        rel="stylesheet"
        href="https://fonts.googleapis.com/icon?family=Material+Icons"
      />
      <link
        rel="stylesheet"
        href="https://code.getmdl.io/1.3.0/material.indigo-pink.min.css"
      />
      <script defer src="https://code.getmdl.io/1.3.0/material.min.js"></script>
    </dynamic-form>

    <script>
      const questions = [
        {
          key: "name",
          label: "Name",
          value: null,
          validators: [
            { name: "required" },
            { name: "minLength", argument: 2 }
          ],
          control: "textbox",
          type: "text",
          errors: [
            {
              name: "required",
              message: "Please enter a name"
            }
          ]
        }
      ];
      const configuration = {
        styleType: "material",
        buttonText: "Send"
      };
      let dynamicForm = document.querySelector("dynamic-form");
      dynamicForm.setAttribute("configuration", JSON.stringify(configuration));
      dynamicForm.setAttribute("questions", JSON.stringify(questions));
      dynamicForm.addEventListener("getFormValue", ev =>
        console.log(ev.detail)
      );
    </script>
</body>
</html>

Documnetation

Questions

The question input of the dynamic-form is a json string containing an array of questions for example:

[
  {
    key: "name",
    label: "Name",
    value: null,
    validators: [
      { name: "required" },
      { name: "minLength", argument: 2 }
    ],
    control: "textbox",
    type: "text",
    errors: [
      {
        name: "required",
        message: "Please enter a name"
      }
    ]
  },
  {
    key: "email",
    label: "Email",
    value: null,
    validators: [{ name: "required" }, { name: "email" }],
    control: "textbox",
    type: "text",
    errors: [
      {
        name: "required",
        message: "Please enter a email"
      },
      {
        name: "email",
        message: "Please enter a valid email"
      }
    ]
  }
]

The questions of type checkbox can contain options to work as a form array if no options are passed will be a boolean value on checked

radio buttons and selectbox must contain options.

Options keys are te value you want to get from the form and the value is the text to display

the question object will have an interface as describe at the bottom

Error handling

Error are set with name and message in case of using default validation from the validators set at the botton error will follow

{
  name: "required",
  message: "Please enter this field"
}
{
  name: "min",
  message: "The minimun value is 12"
}

With custom validator see full example

Validators

  { name: "min", argument: number }
  { name: "max", argument: number }
  { name: "required", argument: null }
  { name: "email", argument: null }
  { name: "minLength", argument:  number }
  { name: "maxLength", argument:  number }
  { name: "pattern", argument: string }

also custom validators are posible a custom validator is a function that evaluates to a null value if there is there no error or to an object with a key containing the error name set to true for example

function addressValidator(control) {
    return !!control.get("street").value || !!control.get("area").value
      ? null
      : { invalidAddress: true };
  }
   window["addressValidator"] = addressValidator;

control is a abstract control from angular if you need more information follow the angular docs you need to atach the function to the window object so the component can read it and set the definition to true in the validation check the full example

Configuration

Configure the styles and the submit button text

<dynamic-form configuration='{"styleType": "material", "buttonText": "Send"}'></dynamic-form>

Style type

You can style the form with crafted styles by default with no styles or use either material or bootstrap

Interfaces

Configuration

export interface Configuration {
  styleType?: StyleType;
  buttonText?: string;
}

Form Question

import { QuestionValidator } from "./question-validator.interface";
import { QuestionOptions } from "./question-options.interface";
import { QuestionError } from "./question-error.interface";

type control =
  | "textbox"
  | "selectbox"
  | "checkbox"
  | "textarea"
  | "onlyInt"
  | "group";
type type = "text" | "email" | "password" | "number";
export interface FormQuestion<T> {
  value: T;
  key: string;
  label: string;
  control: control;
  type?: type;
  options?: QuestionOptions[];
  validators?: QuestionValidator[];
  errors: QuestionError[];
  group: FormQuestion<T>[];
}

Question Options

export interface QuestionOptions {
  key: string;
  value: string;
}

Question Validators

export interface QuestionValidator {
  name: string;
  argument?: any;
  definition?: boolean;
}

Question Error

export interface QuestionError {
  name: string;
  message: string;
}

Types

StyleType

export type StyleType = "material" | "bootstrap" | "default";

Examples

Material Design

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Test</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">

</head>
<body>
    <script src="node_modules/@bepasquet/dynamic-form/dist/index.js">

   <dynamic-form  >
    <link
        rel="stylesheet"
        href="https://fonts.googleapis.com/icon?family=Material+Icons"
    />
    <link
        rel="stylesheet"
        href="https://code.getmdl.io/1.3.0/material.indigo-pink.min.css"
    />
        <script defer src="https://code.getmdl.io/1.3.0/material.min.js"></script>
    </dynamic-form>

    <script>
      const questions = [
        {
          key: "name",
          label: "Name",
          value: null,
          validators: [
            { name: "required" },
            { name: "minLength", argument: 2 }
          ],
          control: "textbox",
          type: "text",
          errors: [
            {
              name: "required",
              message: "Please enter a name"
            }
          ]
        }
      ];
      const configuration = {
        styleType: "material",
        buttonText: "Send"
      };
      let dynamicForm = document.querySelector("dynamic-form");
      dynamicForm.setAttribute("configuration", JSON.stringify(configuration));
      dynamicForm.setAttribute("questions", JSON.stringify(questions));
      dynamicForm.addEventListener("getFormValue", ev =>
        console.log(ev.detail)
      );
    </script>
</body>
</html>

Bootstrap

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Test</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">

</head>
<body>
    <script src="node_modules/@bepasquet/dynamic-form/dist/index.js">

   <dynamic-form  >
        <link
        rel="stylesheet"
        href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"
        integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm"
        crossorigin="anonymous"
        />

        <script
        src="https://code.jquery.com/jquery-3.2.1.slim.min.js"
        integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN"
        crossorigin="anonymous"
        ></script>
        <script
        src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"
        integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q"
        crossorigin="anonymous"
        ></script>
        <script
        src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"
        integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl"
        crossorigin="anonymous"
        ></script>
    </dynamic-form>

     <script>
      const questions = [
        {
          key: "name",
          label: "Name",
          value: null,
          validators: [
            { name: "required" },
            { name: "minLength", argument: 2 }
          ],
          control: "textbox",
          type: "text",
          errors: [
            {
              name: "required",
              message: "Please enter a name"
            }
          ]
        }
      ];
      const configuration = {
        styleType: "material",
        buttonText: "Send"
      };
      let dynamicForm = document.querySelector("dynamic-form");
      dynamicForm.setAttribute("configuration", JSON.stringify(configuration));
      dynamicForm.setAttribute("questions", JSON.stringify(questions));
      dynamicForm.addEventListener("getFormValue", ev =>
        console.log(ev.detail)
      );
    </script>
</body>
</html>

Full example using material design

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Test</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">

</head>
<body>
    <script src="node_modules/@bepasquet/dynamic-form/dist/index.js">

  <dynamic-form  >
       <link
        rel="stylesheet"
        href="https://fonts.googleapis.com/icon?family=Material+Icons"
    />
    <link
        rel="stylesheet"
        href="https://code.getmdl.io/1.3.0/material.indigo-pink.min.css"
    />
    <script defer src="https://code.getmdl.io/1.3.0/material.min.js"></script>
  </dynamic-form>

    <script>
      function addressValidator(control) {
        return !!control.get("street").value || !!control.get("area").value
          ? null
          : { invalidAddress: true };
      }
      function passwordValidator(control) {
        return control.get("password").value ===
          control.get("confirmPassword").value
          ? null
          : { invalidPassword: true };
      }
      window["addressValidator"] = addressValidator;
      window["passwordValidator"] = passwordValidator;
      const questions = [
        {
          key: "name",
          label: "Name",
          value: null,
          validators: [
            { name: "required" },
            { name: "minLength", argument: 2 }
          ],
          control: "textbox",
          type: "text",
          errors: [
            {
              name: "required",
              message: "Please enter a name"
            }
          ]
        },
        {
          key: "email",
          label: "Email",
          value: null,
          validators: [{ name: "required" }, { name: "email" }],
          control: "textbox",
          type: "text",
          errors: [
            {
              name: "required",
              message: "Please enter a email"
            },
            {
              name: "email",
              message: "Please enter a valid email"
            }
          ]
        },
        {
          key: "phone",
          label: "Phone",
          value: null,
          control: "onlyInt",
          type: "number"
        },
        {
          key: "note",
          label: "Note",
          value: null,
          control: "textarea",
          type: "text"
        },
        {
          key: "isMarried",
          label: "Married",
          value: null,
          control: "checkbox",
          options: []
        },
        {
          key: "gender",
          label: "Gender",
          value: null,
          control: "radio",
          options: [{ key: "m", value: "Male" }, { key: "f", value: "Female" }]
        },
        {
          key: "studies",
          label: "Studies",
          value: null,
          control: "checkbox",
          options: [
            { key: "primary", value: "Primary" },
            { key: "highSchool", value: "High School" },
            { key: "tertiary", value: "Tertiary" },
            { key: "university", value: "University" }
          ]
        },
        {
          key: "idType",
          label: "Indetification",
          value: null,
          control: "selectbox",
          validators: [{ name: "required" }],
          errors: [
            {
              name: "required",
              message: "Please enter an Identification"
            }
          ],
          options: [
            { key: 1, value: "Passport" },
            { key: 2, value: "Driver Licence" }
          ]
        },
        {
          key: "address",
          control: "group",
          validators: [
            {
              name: "addressValidator",
              definition: true
            }
          ],
          errors: [
            {
              name: "invalidAddress",
              message: "Please enter at least one address"
            }
          ],
          group: [
            {
              key: "street",
              label: "Street",
              value: null,
              control: "textbox",
              type: "text"
            },
            {
              key: "area",
              label: "Area",
              value: null,
              control: "textbox",
              type: "text"
            }
          ]
        },
        {
          key: "credentials",
          control: "group",

          validators: [
            {
              name: "passwordValidator",
              definition: true
            }
          ],
          errors: [
            {
              name: "invalidPassword",
              message: "Password and Confirm Password are not the same"
            }
          ],
          group: [
            {
              key: "password",
              label: "Password",
              value: null,
              control: "textbox",
              type: "password",
              validators: [{ name: "required" }],
              errors: [
                {
                  name: "required",
                  message: "Please enter a passowrd"
                }
              ]
            },
            {
              key: "confirmPassword",
              label: "Confirm Password",
              value: null,
              control: "textbox",
              type: "password",
              validators: [{ name: "required" }],
              errors: [
                {
                  name: "required",
                  message: "Please confirm your password"
                }
              ]
            }
          ]
        }
      ];
      const configuration = {
        styleType: "material",
        buttonText: "Send"
      };
      let dynamicForm = document.querySelector("dynamic-form");
      dynamicForm.setAttribute("configuration", JSON.stringify(configuration));
      dynamicForm.setAttribute("questions", JSON.stringify(questions));
      dynamicForm.addEventListener("getFormValue", ev =>
        console.log(ev.detail)
      );
    </script>
</body>
</html>

Advanced

Dynamic forms has the ability to pass inner groups with crafted validation for that you have to define a validator function and attached to the window object and pass the name on the group validator array and the definition set to true here is an example

function addressValidator(control) {
    return !!control.get("street").value || !!control.get("area").value
      ? null
      : { invalidAddress: true };
  }
window["addressValidator"] = addressValidator;
const questions = [{
  key: "address",
  control: "group",
  validators: [
    {
      name: "addressValidator",
      definition: true
    }
  ],
  group: [
    {
      key: "street",
      label: "Street",
      value: null,
      control: "textbox",
      type: "text"
    },
    {
      key: "area",
      label: "Area",
      value: null,
      control: "textbox",
      type: "text"
    }
  ]
}];

Contributing

Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.

Please make sure to update tests as appropriate.

License

MIT