@bepasquet/dynamic-form

3.2.4 • Public • Published

@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

Package Sidebar

Install

npm i @bepasquet/dynamic-form

Weekly Downloads

1

Version

3.2.4

License

MIT

Unpacked Size

433 kB

Total Files

3

Last publish

Collaborators

  • bepasquet