Giter Club home page Giter Club logo

formvuelate-plugin-vee-validate's Introduction

FormVueLate

⚠️ IMPORTANT ⚠️

It makes us very sad but as of June 2022 this repository is officially unmaintained. We do not have the required time and space to make the updates it needs to grow, and the possibly necessary rewrite to bring in new and better features. If anyone wishes to take over and continue with the project, please ping Marina on twitter.com/marinamosti

FormVueLate Logo

FormVueLate NPM codecov Buy us a tree

Visit FormVueLate 3.0's full documentation for more detailed information and examples.

Getting Started

FormVueLate is a zero dependency library that allows you to generate schema-driven forms with extreme ease.

The schema that you use for your form can be as flexible as you need it to be, it can be modified at run-time with an expected reactive result, and can even be fetched directly from you backend’s API.

Important

FormVueLate is a bring-your-own-components library!

We do not provide any base components for your to build your forms. There are numerous component libraries out there that do a great job of providing carefully constructed components for you to use, and FormVueLate does a great job at allowing you to bring those external components to your forms, or even crafting your own.

FormVueLate 2.x

The docs for FormVueLate 2.x can be found here

Installation

To add FormVueLate to your project, start by installing the package through your favorite package manager.

yarn add formvuelate
// OR
npm install formvuelate

Using the SchemaForm component

Now that you have the package in your project, import it to your component.

import { SchemaForm, useSchemaForm } from 'formvuelate'

The SchemaForm requires one prop, schema, which is the meta-data of your form. You must also import the useSchemaForm composable which we will use in our setup function to initialize the form's model where the user's data is kept.

<template>
  <SchemaForm :schema="mySchema" />
</template>

<script>
import { ref } from 'vue'
import { SchemaForm, useSchemaForm } from 'formvuelate'

export default {
  components: { SchemaForm },
  setup () {
    const formModel = ref({})
    useSchemaForm(formModel)

    const mySchema = ref({
      // Schema here
    })

    return {
      mySchema
    }
  }
}
</script>

SchemaForm will automatically update the state within your formModel when your components update.

Official plugins

Lookup Plugin

A mapping and replacement plugin to parse complex schemas into FormVueLate ready structure.

Vee-Validate Plugin

Easily incporate Vee-Validate powered validations into your forms.

Vuelidate Plugin WIP

Easily incorporate Vuelidate powered validations into your forms.

Core team

Marina Mosti
Marina Mosti
Abdelrahman Awad
Abdelrahman Awad

Emeriti

Special thanks to these folks which have provided invaluable contributions to the project.

Licence and Support

This package is Treeware. If you use it in production, then we ask that you buy the world a tree to thank us for our work. By contributing to the Treeware forest you’ll be creating employment for local families and restoring wildlife habitats.

If you want to use paypal, you can make any donations to Marina's Paypal account. All donations recieved here will go directly into buying more trees as well!

formvuelate-plugin-vee-validate's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

formvuelate-plugin-vee-validate's Issues

[QUESTION] How to make sure SchemaFormFactory created the expanded SchemaForm?

Hello team:

This whole concept of having a Form Generator based on a JSON schema is awesome and so far has been a great experience. The documentation is very straightforward.

I am having a problem to understand how to implement the Vee-validate plugin. In Documentation is stated:

"First, import the SchemaFormFactory into your application."

Does it means that this import line should be placed on main.js? I did that and hope that is the correct way.

Then, there is a template example with the three plugin documenting that the order is important.

"The order in which you pass the plugins is important, as they will be applied in the order they are received."

I assumed that this code example can be used as a template for a SFC. I copied the contents and left only the VeeValidatePlugin({})

`

<script> import VeeValidatePlugin from "@formvuelate/plugin-vee-validate"; const SchemaFormWithPlugins = SchemaFormFactory([VeeValidatePlugin()]); export default { name:"SchemaFormWithPlugins", components: { SchemaFormWithPlugins, }, }; </script>

`

Saved as SchemaFormWithPlugins.vue

Then I imported the Component and use it

<template> <SchemaFormWithPlugins :schema="mySchema" v-model="formData" /> </template>

This is the schema:
const mySchema = shallowRef({ banco: { component: FormText, label: "A label", innerClass: "p-field p-col-12 p-md-3", validations: (value) => value && value.length > 10, }, });

And unfortunately, the validation object remains empty. Am I missing something? I assume that Field Validation should be out of the box with the provided validation.

Thanks for the great efforts.

[QUESTION] How to use globally imported components with the plugin?

Hello Team:

I might have found a bug, but first I want to make sure I have followed the instructions correctly. Documentation points out that the Component can be a string, provided it is globally registered:
"You can use the name of the component as a String instead, for example 'FormText', but be aware that the component needs to either be imported globally, or in your file first."

I have taken the BaseInput.vue component, added the validation prop and globally registered in main.js

import { createApp } from "vue"; import BaseInput from "@/path/to/BaseInput"; app.component("base-text", BaseInput); app.mount("#app");

Now the tricky part, should I use the string 'base-text' with the normal SchemaForm the component is rendered:

const schema = shallowRef({ banco: { component: "base-text", label: "A label", }, });
image

However, if I create the SchemaFormWithPlugins with SchemaFormFactory:

const SchemaFormWithPlugins = SchemaFormFactory([VeeValidatePlugin()]);
export default{
 components: {
    SchemaFormWithPlugins,
 }
setup(){
const schema = shallowRef({
      banco: {
        component: "base-text",
        label: "A label",
      },
    })
return {schema}
}
}

The Component does not render.

image

Nonetheless, a locally registered BaseInput in SchemaFormWithPlugins works as expected:

import BaseInput from "@/path/to/BaseInput";
export default {
components: {
    BaseInput,
},
setup(){
const schema = shallowRef({
      banco: {
        component: BaseInput,
        label: "A label",
      },
    })
return {schema}
}

}

image

I wonder if I messing something up.

Thanks team.

Access validation errors outside of SchemaForm component

I want to display a list of all the validation errors on the page, not just under each input. ie

<SchemaForm schema="schema" />
<p>{{veevalidate.errors}}</p>

Is there a global object or something I need to import?

Thanks!

Manually marking a field as invalid after the fact

Is your feature request related to a problem? Please describe.
After submitting a form, the backend may return an error related to one of the fields (e.g. e-mail already in use). I want to signal an error for this specific field, but see no way of doing so.

Describe the solution you'd like
Not sure how the API would look...

Describe alternatives you've considered
Tried adding a new error to the initial-errors prop, but it does not seem to override the validation state.

Additional context

Vee-vaidate crashes when using the nested "subform" array schema

Describe the bug
The function getFromPath in Vee-validate crashes when reaches a nested schema-form in the array-schema example

 {
        component: "schema-form", //SchemaForm,
        model: "subform",
        schema: [
          {
            // validations: yup.string().required(),
            component: "text-input", //FormText,
            label: "Work address",
            model: "address"
          },
          {
            // validations: yup.string().required(),
            component: "text-input", //FormText,
            label: "Work phone",
            model: "phone"
          }
        ]
      }

on the other hand FormVueLate wont recognize the nested.path.model syntax for nested values of Vee Validate

To Reproduce
Steps to reproduce the behavior:

Run the "array based schema example" with a "vee-validate-plugin" component syntax

Expected behavior
Vee validate ignores the scheda-form level without crashing

System Info

  • FormVueLate version: "formvuelate": "^2.0.0",
  • plugins being used with versions: "@formvuelate/plugin-vee-validate": "^1.0.3",

Additional context

Computed form level validation-schema is not reactive

Describe the bug
I am trying to make a computed form-level validation schema, but it does not seem to be reactive.

To Reproduce

it.only("preserves reactivity in computed schemas and validations", async () => {
  const toggle = ref("");
  const SchemaWithValidation = SchemaFormFactory([veeValidatePlugin()]);
  const schema = computed(() => {
    const computedSchema = {
      firstName: {
        label: "First Name",
        component: FormText,
      },
    };
    if (toggle.value === "REQUIRE_EMAIL") {
      return {
        ...computedSchema,
        email: {
          label: "Email",
          component: FormText,
        },
      };
    }

    return computedSchema;
  });

  const validationSchema = computed(() => {
    const computedSchema = {
      firstName: yup.string().required("NAME"),
    };
    if (toggle.value === "REQUIRE_EMAIL") {
      computedSchema.email = yup.string().email().required("EMAIL");
    }
    return yup.object().shape(computedSchema);
  });

  const wrapper = mount({
    template: `
    <SchemaWithValidation :schema="schema" :validation-schema="validationSchema">
      <template #afterForm="{ validation }">
        <span id="test">{{ validation }}</span>
        <button :disabled="!validation.meta.valid"></button>
      </template>
    </SchemaWithValidation>
  `,
    components: {
      SchemaWithValidation,
    },
    setup() {
      const formData = ref({});
      useSchemaForm(formData);

      return {
        schema,
        validationSchema,
      };
    },
  });

  // Only "firstName" shows
  let input = wrapper.findAllComponents(FormText);
  expect(input.length).toBe(1);

  toggle.value = "";
  await flushPromises();

  // Form is invalid (firstName is required)
  const button = wrapper.find("button");
  expect(button.element.disabled).toBe(true);

  // Fill in firstName
  input[0].setValue("name");
  await flushPromises();

  // Form is valid
  expect(button.element.disabled).toBe(false);

  // Show "email"
  toggle.value = "REQUIRE_EMAIL";
  await flushPromises();

  input = wrapper.findAllComponents(FormText);
  expect(input.length).toBe(2);

  // Touch email
  input[1].setValue("");
  await flushPromises();

  // ERROR Form is valid, but should be invalid?
  expect(button.element.disabled).toBe(true);
});

Expected behavior
When the toggle is set to "REQUIRE_EMAIL", which shows the email field and updates the form-level validation schema to require it, I expect the form to be invalid.

Additionally, "touching" the email field does not mark the form as invalid leading me to believe the computed validation schema is not reactive.

System Info

  • FormVueLate version: 3.3.0
  • @formvuelate/plugin-vee-validate version: 2.3.0 (vee-validate: 4.0.0-beta.16)

Reset form validation feature

Is your feature request related to a problem? Please describe.
When I submit a form, I cannot reset form data without triggering validation (eg: required fields).

Describe the solution you'd like
I would like to be able to reset form validation.

Describe alternatives you've considered
Customising VeeValidatePlugin, I was able to add vee-validate's resetForm method exposed by useForm and then access with form component ref :

VeeValidatePlugin.js

    // Create a form context and inject the validation schema if provided
    const { handleSubmit, resetForm } = useForm({
      validationSchema: formAttrs['validation-schema'] || formAttrs.validationSchema,
      initialErrors: formAttrs['initial-errors'] || formAttrs.initialErrors,
      initialDirty: formAttrs['initial-dirty'] || formAttrs.initialDirty,
      initialTouched: formAttrs['initial-touched'] || formAttrs.initialTouched
    });

...

    return {
      ...baseReturns,
      formBinds: computed(() => {
        return {
          ...baseReturns.formBinds.value,
          onSubmit
        };
      }),
      parsedSchema: computed(() => formSchema),
      resetForm
    };

MyView.vue

              <SchemaFormWithValidation
                ref="form"
                class="space-y-6"
                :schema="forgotPasswordFormSchema"
                v-model="forgotPasswordFormData"
                @submit="sendResetPasswordMail"
              >

...

    const sendResetPasswordMail = () => {
      sendResetPasswordMailMutation(forgotPasswordFormData.value);
      forgotPasswordFormData.value.email = '';
      (form.value as any).resetForm();
    };

I'm not sure that this is the correct way to do it thought, or even if the actual plugin version offers this possibility.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.