---
name: MagaForm
route: /components/maga-form
menu: Components ⚡️
---

import { Playground, Props } from "docz";
import { Button } from "semantic-ui-react";
import MagaForm from "../index.tsx";
import { mountSelectRangeValues, formTemplate } from "../util.tsx";
import "../styles/index.css";
import "../styles/react-datepicker.css";

# MagaForm

Formulário padrão capaz de receber como prop um array onde cada objeto
é um campo do formulário e que tenha validações, tipagem, valor do label e tamanho dele em relação ao layout da grid.

    import { MagaForm } from 'maga-components'

    <MagaForm
        formTemplate={FORM_TEMPLATE}
        onSubmit={data => {
          console.log(data);
        }}
    />

## Props

<Props of={MagaForm} />

## FormTemplate

### Layout config

| Property | Type     | Required | Default | Description         |
| -------- | -------- | -------- | ------- | ------------------- |
| row      | object[] | true     | {}      | Linha do formulário |

### Campos

| Property         | Type    | Required | Default          | Description                                                                                            |
| ---------------- | ------- | -------- | ---------------- | ------------------------------------------------------------------------------------------------------ |
| label            | string  | true     | ""               | Label do campo                                                                                         |
| name             | string  | true     | ""               | Referência do campo                                                                                    |
| type             | string  | true     | text             | Tipos válidos: "checkbox" "date" "dropdown" "password" "radio" "radioGroup" "select" "text" "textArea" |
| value            | string  | true     | ""               | Valor inicial do campo                                                                                 |
| placeholder      | string  | true     | ""               | PlaceHolder do campo                                                                                   |
| mask             | string  | false    | "999.999.999-99" | Mascara do campo                                                                                       |
| maxLength        | number  | false    | 250              | Tamanho máximo do campo                                                                                |
| required         | boolean | true     | true             | Campo obrigatório / opcional                                                                           |
| validations      | object  | true     | {}               | Validações do campo                                                                                    |
| validationErrors | object  | true     | {}               | Mensagens de erro do campo                                                                             |
| width            | number  | true     | 4                | Tamanho da coluna do campo [Grid com 16 colunas]                                                       |

### Submeter formulário

| Property | Type   | Required | Default  | Description                      |
| -------- | ------ | -------- | -------- | -------------------------------- |
| submit   | string | true     | "Salvar" | Botão para submeter o formulário |

## Validações

| Validations            | Descrição                                                                          | Exemplo                          |
| ---------------------- | ---------------------------------------------------------------------------------- | -------------------------------- |
| isDefaultRequiredValue | Campo obrigatório por padrão                                                       | { isDefaultRequiredValue: true } |
| isExisty               | Se o valor existe                                                                  | { isExisty: true }               |
| matchRegexp            | Com expressão regular                                                              | { matchRegexp: "/\w+/" }         |
| isUndefined            | Se o valor é undefined                                                             | { isUndefined: true }            |
| isEmptyString          | Se o valor é vazio                                                                 | { isEmptyString: true }          |
| isEmail                | Se o valor é um e-mail                                                             | { isEmail: true }                |
| isUrl                  | Se o valor é uma URL                                                               | { isUrl: true }                  |
| isTrue                 | Se o valor é = true                                                                | { isTrue: true }                 |
| isFalse                | Se o valor = false                                                                 | { isFalse: true }                |
| isNumeric              | Se o valor é um número                                                             | { isNumeric: true }              |
| isAlpha                | Se o valor é um conjunto de caracteres de A a Z, incluindo maiúsculas e minúsculas | { isAlpha: true }                |
| isAlphanumeric         | Se o valor é alfanumérico                                                          | { isAlphanumeric: true }         |
| isInt                  | Se o valor é inteiro                                                               | { isInt: true }                  |
| isFloat                | Se o valor é float                                                                 | { isFloat: true }                |
| isWords                | Se o valor é uma palavra incluido espaços e tabs                                   | { isWords: true }                |
| isSpecialWords         | Se o valor tem apenas letras, incluindo letras especiais (a-z, ú, ø, æ, å)         | { isSpecialWords: true }         |
| isLength               | Se o valor tem determinado tamanho                                                 | { isLength: 8 }                  |
| equals                 | Se o valor é igual a "x"                                                           | { equals: 4 }                    |
| equalsField            | Se o valor é igual o valor de outro campo                                          | { equalsField: "password" }      |
| maxLength              | Se o tamanho de caracteres do valor é <= que o tamanho máximo                      | { maxLength:10 }                 |
| minLength              | Se o tamanho de caracteres do valor é >= que o tamanho mínimo                      | { minLength:3 }                  |

## Uso básico

<Playground>
  <MagaForm
    refForm="form1"
    title="Título do cadastro"
    formTemplate={[
      {
        row: {
          fields: [
            {
              label: "Nome",
              name: "name",
              type: "text",
              value: "",
              placeholder: "",
              defaultValue: "daniel",
              maxLength: 100,
              required: true,
              validations: { minLength: 3 },
              validationErrors: {
                isDefaultRequiredValue: "O nome é obrigatório",
                minLength: "Deve possuir no minimo 3 caracteres",
              },
              width: 4,
              disabled: true             
            },
            {
              label: "CPF",
              name: "cpf",
              type: "text",
              value: "",
              placeholder: "999.999.999-99",
              defaultValue: "09818429680",
              maxLength: 14,
              mask: "999.999.999-99",
              required: true,
              validations: {},
              validationErrors: {
                isDefaultRequiredValue: "O CPF é obrigatório",
              },
              width: 4
            },
            {
              label: "Celular",
              name: "cellPhone",
              type: "text",
              value: "",
              placeholder: "(16) 9 9999-9999",
              maxLength: 15,
              mask: "(99) \\9 9999 9999",
              maskChar: " ",
              required: true,
              validations: {},
              validationErrors: {
                isDefaultRequiredValue: "O celular é obrigatório",
              },
              width: 4,
            },
            {
              label: "Telefone",
              name: "phone",
              type: "text",
              value: "",
              maskChar: "_",
              placeholder: "(16) 9999-9999",
              mask: "(99) 9999-9999",
              raw: true,
              required: false,
              validations: {
                minLength: 10,
              },
              validationErrors: {
                minLength: "Digite ao menos 10 caracteres",
                maxLength: "Digite no máximo 10 caracteres",
              },
              width: 4,
            },
          ],
        },
      },
      {
        row: {
          fields: [
            {
              label: "Data de nascimento",
              name: "birthDate",
              type: "date",
              value: "",
              dateFormat: "dd/MM/yyyy",
              defaultValue: "2019-04-23",
              placeholder: "",
              maxLength: 15,
              required: true,
              validations: {},
              validationErrors: {
                isDefaultRequiredValue: "A data de nascimento é obrigatória",
              },
              width: 4,
            },
            {
              label: "Status",
              name: "status",
              type: "select",
              value: "",
              placeholder: "",
              required: true,
              validationErrors: {
                isDefaultRequiredValue: "O status é obrigatório",
              },
              width: 4,
              data: [
                {
                  key: 1,
                  text: "Ativo",
                  value: 1,
                },
                {
                  key: 2,
                  text: "Desativado",
                  value: 2,
                },
              ],
              multiple: false,
            },
            {
              label: "Habilidades",
              name: "multipleItens",
              type: "select",
              value: "images",
              placeholder: "",
              required: true,
              validationErrors: {
                isDefaultRequiredValue: "Selecione ao menos uma habilidade",
              },
              width: 6,
              data: [
                {
                  key: 1,
                  text: "CSS",
                  value: "CSS",
                },
                {
                  key: 2,
                  text: "Go",
                  value: "Go",
                },
                {
                  key: 3,
                  text: "HTML",
                  value: "HTML",
                },
                {
                  key: 4,
                  text: "Java",
                  value: "Java",
                },
                {
                  key: 5,
                  text: "JavaScript",
                  value: "JavaScript",
                },
                {
                  key: 6,
                  text: "Python",
                  value: "Python",
                },
              ],
              multiple: true,
            },
          ],
        },
      },
      {
        row: {
          fields: [
            {
              label: "Selecione seus interesses",
              name: "interestsField",
              type: "select",
              defaultData: [],
              placeholder: "Interesses",
              required: true,
              search: true,
              validationErrors: {
                isDefaultRequiredValue: "Selecione ao menos um interesse",
              },
              width: 8,
              data: [
                {
                  key: 3,
                  text: "Novela",
                  value: 3,
                },
                {
                  key: 4,
                  text: "Séries",
                  value: 4,
                },
                {
                  key: 5,
                  text: "Música",
                  value: 5,
                },
                {
                  key: 6,
                  text: "Games",
                  value: 6,
                },
              ],
              multiple: true,
              grouped: true,
              uniquePerGroup: true,
              handleChange: (e, data, value, groupedValues) => {
                console.log(
                  "FORM TEMPLATE HANDLE CHANGE",
                  e,
                  data,
                  value,
                  groupedValues
                );
              },
            },
            {
              label: "Selecione seus interesses",
              name: "interestsField_2",
              type: "select",
              defaultData: [
                {
                  key: 1,
                  text: "Futebol",
                  value: 1,
                },
                {
                  key: 2,
                  text: "Cinema",
                  value: 2,
                },
              ],
              placeholder: "Interesses",
              required: true,
              search: true,
              validationErrors: {
                isDefaultRequiredValue: "Selecione ao menos um interesse",
              },
              width: 8,
              data: [
                {
                  key: 1,
                  text: "Futebol",
                  value: 1,
                },
                {
                  key: 2,
                  text: "Cinema",
                  value: 2,
                },
                {
                  key: 3,
                  text: "Novela",
                  value: 3,
                },
                {
                  key: 4,
                  text: "Séries",
                  value: 4,
                },
                {
                  key: 5,
                  text: "Música",
                  value: 5,
                },
                {
                  key: 6,
                  text: "Games",
                  value: 6,
                },
              ],
              multiple: true,
              grouped: true,
              uniquePerGroup: true,
              handleChange: (e, data, value, groupedValues) => {
                console.log(
                  "FORM TEMPLATE HANDLE CHANGE",
                  e,
                  data,
                  value,
                  groupedValues
                );
              },
            },
          ],
        },
      },
      {
        row: {
          fields: [
            {
              label: "Profissão",
              name: "occupation",
              type: "radio",
              variation: "checkbox",
              value: "",
              placeholder: "",
              required: true,
              validationErrors: {
                isDefaultRequiredValue: "A profissão é obrigatória",
              },
              data: [
                {
                  text: "Developer",
                  value: "developer",
                },
                {
                  text: "Product Owner",
                  value: "product_owner",
                },
                {
                  text: "Squad Lead",
                  value: "squad_lead",
                },
              ],
              width: 8,
            },
            {
              label: "Descrição",
              name: "description",
              type: "textArea",
              value: "",
              placeholder: "",
              required: true,
              validations: { minLength: 3 },
              validationErrors: {
                isDefaultRequiredValue: "A descrição é obrigatório",
                minLength: "Deve possuir no minimo 3 caracteres",
              },
              width: 8,
            },
          ],
        },
      },
      {
        row: {
          fields: [
            {
              label: "Aceito os termos de uso",
              name: "agree",
              type: "checkbox",
              value: "",
              placeholder: "",
              required: true,
              defaultChecked: true,
              validations: { isTrue: true },
              validationErrors: {
                isTrue: "Isso não é negociável",
                isDefaultRequiredValue: "Você precisa marcar essa seleção",
              },
              width: 16,
            },
          ],
        },
      },
      {
        row: {
          fields: [
            {
              label: "Salvar",
              name: "phone",
              type: "submit",
              value: "",
              placeholder: "",
              color: "green",
              icon: "save",
              floated: "left",
              required: false,
              validations: {},
              validationErrors: {},
              width: 16,
            },
          ],
        },
      },
    ]}
    onSubmit={(data) => {
      alert(JSON.stringify(data));
    }}
  />
</Playground>

## Agrupamento multiSelectArea

<Playground>
  <MagaForm
    refForm="form3"
    title="Título do cadastro"
    formTemplate={[
      {
        row: {
          fields: [
            {
              label: "Nome",
              name: "name",
              type: "text",
              value: "",
              placeholder: "",
              defaultValue: "dsadsadsaddas",
              maxLength: 100,
              required: true,
              validations: {},
              validationErrors: {
                isDefaultRequiredValue: "O nome é obrigatório",
              },
              width: 16,
            },
          ],
        },
      },
      {
        row: {
          fields: [
            {
              label: "Selecione os grupos de habilidades",
              name: "multipleItens",
              type: "multiSelectArea",
              value: "images",
              placeholder: "",
              required: true,
              minLength: 3,
              validationErrors: {
                isDefaultRequiredValue: "Selecione ao menos uma habilidade",
                minLength: "Deve conter 3 ítens selecionados",
              },
              width: 8,
              data: [
                {
                  id: 1,
                  label: "CSS",
                },
                {
                  id: 2,
                  label: "Go",
                },
                {
                  id: 3,
                  label: "HTML",
                },
                {
                  id: 4,
                  label: "Java",
                },
                {
                  id: 5,
                  label: "JavaScript",
                },
                {
                  id: 6,
                  label: "Python",
                },
              ],
              defaultData: [
                {
                  id: 1,
                  label: "CSS",
                },
                {
                  id: 2,
                  label: "Go",
                },
              ],
              multiple: true,
              grouped: true,
            },
          ],
        },
      },
      {
        row: {
          fields: [
            {
              label: "Salvar",
              name: "phone",
              type: "submit",
              value: "",
              placeholder: "",
              color: "green",
              icon: "save",
              floated: "right",
              required: false,
              validations: {},
              validationErrors: {},
              width: 16,
            },
          ],
        },
      },
    ]}
    onChange={(data) => {
      console.log(JSON.stringify(data));
    }}
    onSubmit={(data) => {
      alert(JSON.stringify(data));
    }}
  />
</Playground>

## Agrupamento por linha

<Playground>
  <MagaForm
    refForm="form4"
    title="Título do cadastro"
    formTemplate={[
      {
        row: {
          fields: [
            {
              label: "Operação",
              name: "operationType",
              type: "select",
              value: "",
              defaultValue: 1,
              placeholder: "",
              maxLength: 100,
              required: true,
              validationErrors: {
                isDefaultRequiredValue: "A operação é obrigatória",
              },
              width: 6,
              data: [
                {
                  key: 1,
                  value: 1,
                  text: "RODO",
                },
                {
                  key: 2,
                  value: 2,
                  text: "COURIER",
                },
              ],
            },
            {
              label: "Nome",
              name: "description",
              type: "text",
              value: "",
              defaultValue: "Turno 1",
              placeholder: "",
              maxLength: 100,
              required: true,
              validations: { minLength: 3 },
              validationErrors: {
                isDefaultRequiredValue: "O nome é obrigatório",
                minLength: "Deve possuir no minimo 3 caracteres",
              },
              width: 10,
            },
          ],
        },
      },
      {
        row: {
          fields: [
            {
              label: "Frequência",
              name: "frequency",
              type: "multiSelectArea",
              value: "",
              defaultValue: "",
              placeholder: "",
              maxLength: 100,
              required: true,
              validationErrors: {
                isDefaultRequiredValue: "A frequência é obrigatória",
              },
              width: 16,
              defaultData: [],
              data: [
                {
                  id: 1,
                  label: "Segunda",
                },
                {
                  id: 2,
                  label: "Terça",
                },
                {
                  id: 3,
                  label: "Quarta",
                },
                {
                  id: 4,
                  label: "Quinta",
                },
                {
                  id: 5,
                  label: "Sexta",
                },
                {
                  id: 6,
                  label: "Sábado",
                },
                {
                  id: 7,
                  label: "Domingo",
                },
              ],
              multiple: true,
              grouped: true,
            },
          ],
        },
      },
      {
        row: {
          fields: [
            {
              label: "Horário de carregamento",
              as: "h3",
              icon: "time",
              type: "header",
              color: "blue",
            },
          ],
        },
      },
      {
        row: {
          grouped: true,
          groupName: "range",
          fields: [
            {
              label: "Início",
              name: "start",
              type: "select",
              value: "",
              placeholder: "",
              width: 6,
              data: mountSelectRangeValues(),
              defaultValue: "00:00",
              required: true,
              validationErrors: {
                isDefaultRequiredValue: "O horário inicial é obrigatório",
              },
            },
            {
              label: "Fim",
              name: "end",
              type: "select",
              value: "",
              placeholder: "",
              width: 6,
              data: mountSelectRangeValues(),
              defaultValue: "00:00",
              required: true,
              validationErrors: {
                isDefaultRequiredValue: "O horário final é obrigatório",
              },
            },
          ],
        },
      },
      {
        row: {
          fields: [
            {
              label: "Salvar",
              name: "action",
              type: "submit",
              value: "",
              placeholder: "",
              color: "green",
              icon: "save",
              floated: "right",
              validations: {},
              validationErrors: {},
              width: 16,
            },
          ],
        },
      },
    ]}
    onSubmit={(data) => {
      console.log(JSON.stringify(data));
    }}
  />
</Playground>

## Range de datas

<Playground style={{ height: '600px'}}>
  <MagaForm
    refForm="form5"
    title="Título do cadastro"
    formTemplate={[
        {
          row: {
            fields: [
              {
                label: "Selecione um intervalo de datas",
                name: "range",
                type: "dateRange",
                dateFormat: "DD/MM/YYYY",
                defaultValue: "19/04/2020 - 20/04/2020",
                value: "",
                placeholder: "De - até",
                width: 16,
                required: true,
                validationErrors: {
                  isDefaultRequiredValue: "O campo de data é obrigatório",
                },
              },
            ],
          },
        },
        {
          row: {
            fields: [
              {
                label: "Salvar",
                name: "phone",
                type: "submit",
                value: "",
                placeholder: "",
                color: "green",
                icon: "save",
                floated: "right",
                required: false,
                validations: {},
                validationErrors: {},
                width: 16,
              },
            ],
          },
        },
    ]}
    onChange={(data) => {
      console.log(JSON.stringify(data));
    }}
    onSubmit={data => {
      alert(JSON.stringify(data));
    }}
  />
</Playground>