Git Product home page Git Product logo

form-backend-validation's Introduction

An easy way to validate forms using back end logic

Latest Version on NPM Software License Build Status npm

Wouldn't it be great if you could just use your back end to validate forms on the front end? This package provides a Form class that does exactly that. It can post itself to a configured endpoint and manage errors. The class is meant to be used with a Laravel back end.

Take a look at the usage section to view a detailed example on how to use it.

The code of this package is based on the Object-Oriented Forms lesson in the Vue 2.0 series on Laracasts.

Support us

We invest a lot of resources into creating best in class open source packages. You can support us by buying one of our paid products.

We highly appreciate you sending us a postcard from your hometown, mentioning which of our package(s) you are using. You'll find our address on our contact page. We publish all received postcards on our virtual postcard wall.

Install

You can install the package via yarn (or npm):

yarn add form-backend-validation

By default, this package expects axios to be installed (unless you're using your own http library, see the Options section for that).

yarn add axios

Usage

You can find an example implementation with Laravel and Vue in the spatie/form-backend-validation-example-app repo.

Screenshot

import Form from 'form-backend-validation';

// Instantiate a form class with some values
const form = new Form({
    field1: 'value 1',
    field2: 'value 2',
    person: {
        first_name: 'John',
        last_name: 'Doe',
    },
});

// A form can also be initiated with an array
const form = new Form(['field1', 'field2']);

// Submit the form, you can also use `.put`, `.patch` and `.delete`
form.post(anUrl)
   .then(response => ...)
   .catch(response => ...);

// Returns true if request is being executed
form.processing;

// If there were any validation errors, you easily access them

// Example error response (json)
{
    "errors": {
        "field1": ['Value is required'],
        "field2": ['Value is required']
    }
}

// Returns an object in which the keys are the field names
// and the values array with error message sent by the server
form.errors.all();

// Returns true if there were any error
form.errors.any();

// Returns object with errors for the specified keys in array.
form.errors.any(keys);

// Returns true if there is an error for the given field name or object
form.errors.has(key);

// Returns the first error for the given field name
form.errors.first(key);

// Returns an array with errors for the given field name
form.errors.get(key);

// Shortcut for getting the first error for the given field name
form.getError(key);

// Clear all errors
form.errors.clear();

// Clear the error of the given field name or all errors on the given object
form.errors.clear(key);

// Returns an object containing fields based on the given array of field names
form.only(keys);

// Reset the values of the form to those passed to the constructor
form.reset();

// Set the values which should be used when calling reset()
form.setInitialValues();

// Populate a form after its instantiation, the populated fields will override the initial fields
// Fields not present at instantiation will not be populated
const form = new Form({
    field1: '',
    field2: '',
});

form.populate({
    field1: 'foo',
    field2: 'bar',
});

Options

The Form class accepts a second options parameter.

const form = new Form({
    field1: 'value 1',
    field2: 'value 2',
}, {
    resetOnSuccess: false,
});

You can also pass options via a withOptions method (this example uses the create factory method.

const form = Form.create()
    .withOptions({ resetOnSuccess: false })
    .withData({
        field1: 'value 1',
        field2: 'value 2',
    });

resetOnSuccess: bool

Default: true. Set to false if you don't want the form to reset to its original values after a succesful submit.

http: Object

By default this library uses axios for http request. If you want, you can roll with your own http library (or your own axios instance).

Advanced! Pass a custom http library object. Your http library needs to adhere to the following interface for any http method you're using:

method(url: string, data: Object): Promise<Response>

Supported http methods are get, delete, head, post, put & patch.

If you want to see how the http library is used internally, refer to the Form class' submit method.

Working with files

The form handles file inputs too. The data is then sent as FormData, which means it's encoded as multipart/form-data.

Some frameworks (like Laravel, Symfony) can't handle these incoming requests through other methods than POST, so you might need to take measures to work around this limitation. In Laravel or Symfony, that would mean adding a hidden _method field to your form containing the desired HTTP verb.

Changelog

Please see CHANGELOG for more information what has changed recently.

Testing

$ npm run test

Contributing

Please see CONTRIBUTING for details.

Security

If you discover any security related issues, please contact Freek Van der Herten instead of using the issue tracker.

Postcardware

You're free to use this package, but if it makes it to your production environment we highly appreciate you sending us a postcard from your hometown, mentioning which of our package(s) you are using.

Our address is: Spatie, Kruikstraat 22, 2018 Antwerp, Belgium.

We publish all received postcards on our company website.

Credits

Initial code of this package was copied from Jeffrey Way's Vue-Forms repo.

The idea to go about this way of validating forms comes from Laravel Spark.

License

The MIT License (MIT). Please see License File for more information.

form-backend-validation's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

form-backend-validation's Issues

2.3.3 Update broke my inputs.

I was upgrading frontend packages on a project.

After upgrading, when I type into text fields not all my keypresses get registered (or they do get registered but something is messing up the reactivity). Some characters get entered but most of them don't.

Details relevant to bug:

My opening form tag looks like this:

<form @submit.prevent="onSubmitSignup" @keydown="form.errors.clear($event.target.id)" novalidate>

If I'm using 2.3.3, I can change it to @keyup and the problem goes away but @keydown is clearly better used in this situation.

I tried downgrading to 2.3.2, the problem went away.

I use the Buefy component library. There's a possibility that [email protected] conflicts with it, but I currently have no idea what it could be.

Here are the exact versions of the packages involved (taken from lock file):

  • buefy 0.6.5
  • form-backend-validation 2.3.3
  • vue 2.5.16

CodeSandbox reproduction

You can fork it on CodeSandbox without creating an account. It will allow you to remove and install dependencies from the sidebar to try changing the package versions.

https://codesandbox.io/s/kow33p53m7

Update

Tested against 2.3.5, bug still exists.

Issue with errors

Hi.

I´m using your component in a project. It seems to be a bug rendering errors:

In my Vue file:
{{ form.errors.all() }}
Output:
{ "message": "The given data was invalid.", "errors": { "name": [ "The name field is required." ] } }

But if I try to get the specific key-error with this command: {{ form.getError('name') }} nothing is displayed.

Any clue what I´m doing wrong?

screen shot 2017-08-20 at 13 59 36

detecting a dirty form

I'm looking for a way to determine if a form is "dirty" ie: any of the original data has changed. Is there such a way or could that be added as a flag into Form.js?

Suggestion/feature this.form.only(...keys)

Feature description:

this.form.only(...keys)

How would it work?

Similar to how Laravel's request()->only() works.

I saw in the source of this package that there's already a this.form.data() method.

Basically it's just that but you can pass it an array of fields that it should return.


Example usage:

I have a use case where I need to $emit only the certain fields from large forms to another Vue component.

A method like this would greatly simplify the process.

const fields = {
    foo: this.form.foo,
    bar: this.form.bar
};

// example usage of only()
// const fields = this.form.only(['foo', 'bar']);

this.form.post('/endpoint')
    .then((response) => window.eventBus.$emit('event', fields))
    .catch((error) => console.log(error.response));

Util.js bug(?)

When i add the form-backend package with npm/yarn, the form-backend-validation/dist/util.js file is automatically is created. It seems like the util.js file which is created is a old file without the multiple file upload changes, which causes error with uploading multiple files.

If i delete the util.js file everything works. I have tried to rebuild the dist manually with npm run build, but the util.js file is not added then. It might be some odd cache issues on my machines, but i have tried on two different Macs and cleared the yarn cache.

screen shot 2018-03-01 at 22 11 26

Make it optional to initiate data

Hi, and thanks for a great lib!

I have come across a use-case where it would be useful to not have to initiate all properties up front. It's a create-form with lots of form fields, where having to initiate all of them would be cumbersome. This is Laravel and what we would like to do is to pass some initial values by serializing a new model, but by doing that the attributes that are not set will not be serialized.

The use-case is somewhat similar to this issue in Vue where they eventually changed a behavior in Vue 2: vuejs/vue#5932 (comment)

When looking through the code it struck me that you are doing some work in guardAgainstReservedFieldName() to allow setting properties directly on the Form class, so my understanding is that is not as simple as moving the form data to separate object on the Form class.

Form empty values are omitted on submit

objectToFormData omits empty values from the form object. This is inconsistent behaviour because objectToFormData is getting called only when there is a File in the form. If there is not a File, empty values are posted. This has a major effect on data been validated at the backend.

Maybe the code below should be added at the top of objectToFormData

if (object === null || object === 'undefined' || object.length === 0) {
  return formData.append(parent, object);
}

Work with inertia.js

Hi,

Ia am trying to use this library with inertiajs, however when providing inertia as the http client it doesn't return the response object upon success.

For example:

// form object was previously built

try {
    this.form.errors.clear();

    await this.form.withOptions({http: this.$inertia, resetOnSuccess: false}).post('/login');

    this.$toastr.success('Welcome back');
} catch (error) {
    console.error(error); // logs "response is undefined"
    this.$toastr.error('Failed to log in');
}

The error happens due to lines 198-200 that tires to access the response.data object after a successful ajax call.

As inertiajs does not return the response after a visit those lines fail even if the request succeeds.

I guess if we change those lines to:

// Form.js (lines 196-201)
.then(response => {
    this.processing = false;
    this.onSuccess(response && response.data);

    resolve(response && response.data);
})

It would work well with inertia.

I didn't make a PR as I don't know how to test this case. If this is a desired feature and someone could give me a hint on how to test it I will submit a PR.

One other option is to open a PR in the inertiajs project so the promise in its setPage method can resolve with a return value (For example return {status: 200, data: page};), to work better with this library.

Thanks for the great library.

share across all childs

Hello,

so for example we have id="app-form"
but how do I access this 'form' object from within the components?

I'd also like to alter form from there - since I would like to reset errors etc.

Wrong result on errors.has

Hi,

Awesome package. Is it up to date with Laravel 5.6? Because when I do:

form.errors.has('name')

I get this:

[ "The email to field is required." ]

I would expect:

The email to field is required.

Any idea? Thankyou!

init with errors

Hello,

this is indeed nice package, already using it in few popup forms.
When submission goes ajax-only.

But now we came with some situations. where we want to 'reload' the page actually.
What do you think, is there a change something like:
constructor(data, options, errors) { }

could be added to the constructor?
Is this something you think could be beneficial?
Also - maybe you have some more ideas on how this can be solved using current package.

If that would be added, we could just json_encode the errors from validation and pass them to form object.

Thank you!

"File is not defined" error when used wit nuxtjs ssr

Just installed package @2.3.6 (2.3.7 is not sync with npm yet). With a basic use I am getting this error
"File is not defined"

import Form from 'form-backend-validation'

data(){
    return {
        form: new Form ({
            email:'',
            password:''
        })
     }
  }

image

form.errors.get / form.errors.has aren't working?

Calling form.errors.all() returns

{ 
  "message": "The given data failed to pass validation.", 
  "errors": { "field1": [ "The field1 may not be greater than 2 characters." ] }
}

But trying to access it via form.errors.get('field1') or form.errors.has('field1') returns nothing. What am I doing wrong?

Frontend and Backend Validation

I have been looking for a package that shares validation rules between the frontend and backend. Have you seen anything like this?

File upload

The new file upload does it only support a single file upload?

This works:
form.file = $event.target.files[0]

This don't work:
this.form.file = e.target.files || e.dataTransfer.files;
form.file = $event.target.files

[Discussion] Detect form changes

I think it will be great feature if we are able to determine forms changes, for example displaying warning about losing data.

Here is my possible realization:

hasChanges() {
    const { diff } = require('deep-diff');
    const initial = {};

    for (const property in this.initial) {
        initial[property] = this.initial[property];
    }
    return diff(this.data(), initial) !== undefined;
}

But there is two things that I don't like:

  1. import library for one signle thing
  2. This methods repeat data method to get initial properties

For second point I can create method that will accept field name

[BUG] Request is not handled by Laravel when sending file in array

Hmm, I have a strange problem with uploading files.

I have a "block constructor" that dynamically adds new blocks to fill in, including images. But Laravel does not see files until there is at least one file outside of the dynamic array.

form: new Form({
    test: '',
    name: '',
    text: [],
    _method: 'PUT',
}, {
    resetOnSuccess: false,
}),

"test" is any file you want
"text" consists of the following structure
image
"image" is a single file with an image, while there is no "test" field for some reason Laravel writes that no files were loaded

Gist example: https://gist.github.com/zKoz210/b5336d804d41e2f21ab0a6a88a0850a2

Form goes to catch on 200 response

Hello,

Probably yet another stupid question :D

I'm able to validate and display the errors on the form.
However, after fixing the errors (entering the fields), and re-submitting the form, it still goes into the catch callback. Yet in the network tab I see a 200 ok reponse from laravel. And my resource is created correctly in the database.

I'm not sure why it doesn't go into the then callback.

this.form.post(route('api.page.page.store'))
    .then(response => {
        this.loading = false;
        vm.$message({
            type: 'success',
            message: response.data.message
        });
        window.location = route('admin.page.page.index');
    })
    .catch(error => {
        this.loading = false;
        vm.$notify.error({
            title: 'Error',
            message: 'There are some errors in the form.'
        });
    });

Is there something else to do?

Thanks

Edit: even when entering the form correctly from the first time, ie it never went into the catch callback, it stills goes into it, even though laravel returns a 200.

Edit: here is the full onSubmit method called.

Passing HTTP object to the form

Hi. I am currently using

form: form({
  label: "",
  anotherLabel: ""
}, {
    http: httpClient
   }
)

approach to pass my custom http client library.
This doesn't scale up well and leads to repetitive code. Can someone please show me a better way to do this.

Support array of objects deep cloning

Current implementation of cloneDeep does not support deep cloning for array of objects since the newly created array contains the references to the original array objects instead of objects itself.

I run into a case while trying to reset the form. Form data contained an array of objects (many-to-1 relationship) was binded to a Vue model. After call to setInitialValues and array modification, calling form.reset() did not revert data back to initial state.

Below is a potential solution to the problem. The array case of cloneDeep should be replaced by something like the following:

 if (Array.isArray(object)) {
   const clone = [];

    for (const key in object) {
      if (object.hasOwnProperty(key)) {
        clone[key] = cloneDeep(object[key]);
     }
  }

  return clone;
}

Also, copying of File objects should be taken into account for object type cloning. For example

if (object instanceof File || object instanceof FileList) {
    return object;
}

Pass arbitrary options to Axios

Hi!

I'm in a case where I have to change axios prop responseType to blob, but I can't find any way to pass arbitrary options to axios. It would be nice if submit could handle this like below:

    submit(requestType, url, options) {
        this.__validateRequestType(requestType);
        this.errors.clear();
        this.processing = true;
        this.successful = false;

        return new Promise((resolve, reject) => {
            this.__http[requestType](
                url,
                this.hasFiles() ? objectToFormData(this.data()) : this.data(),
                options
            )
       ...

Solution is backward compatible. Of course, restful api methods (post,put, etc.) also have to change.

Support for axios interceptors?

I am using this package along with tymon/jwt-auth in the backend. I was able to implement axios interceptors to catch certain error responses from jwt-auth.

However, on requests where I use the Form class instead of plain axios, I am unable to intercept the error responses. How do I implement this?

Note: I am aware that when using this package, the data can be accessed through error.data instead of error.response.data so I am sure that I am not incorrectly accessing the data.

Typo in example of `form.populate()` in readme?

Great package, thank you! The readme says that when using form.populate() “the populated fields won’t override the initial fields.” Is it supposed to say they will override the initial fields?

I'm setting initial values and calling form.populate(), and it definitely does override them (which is what I would expect, and what I want). As far as I can tell from the merge() and cloneDeep() helpers, this is the intended behaviour.

Empty errors

Hello,

I'm trying to setup this package with vuejs. However I'm having issues displaying the errors.

My form data is contained inside the page field.

const form = new Form(this.page);
form.post(route('api.page.page.store'));

console.log(form.errors.all());

This returns {}
image

However, in my network tab I do see the errors:
image

When using the "manual" way, I can access the errors like so:

axios.post(route('api.page.page.store'), this.page)
    .then(response => {
        console.log(response);
    })
    .catch(response => {
        console.log(response.response.data);
    })

Am I missing something?

Thanks!

Edit: this is on laravel 5.5 and 2.0.1 of this package.

Handle fetching error message for array validation

The issue in a nutshell is as follows.

if I am sending a request to the server that looks like this.

 'dates' => [ 
     ['starts_at' =>  '09:00', 'ends_at' => '16:00'],
]

I can properly check if the error for dates exists

this.form.has('dates') // true

The issue is when I try to get the error message which will be returned form Laravel as dates.0.starts_at and dates.0.ends_at

so when I try to fetch that error message

this.form.errors.first('dates') // ''
this.form.errors.get('dates') // [ ]

which is not ideal.

I suggest changing the first(field) method to be the following.

  first(field) {
    let message = this.get(field)[0]

    if (message === undefined) {
      const errors = Object.keys(this.errors).filter(
        e => e.startsWith(`${field}.`) || e.startsWith(`${field}[`)
      )
      if (errors.length > 0) {
        message = this.first(errors[0])
      }
    }

    return message
  }

so that if this.form.has('dates') returns true, I can get the error message using this.form.first('dates) rather than having to know the index of the error.

What are your thoughts?

Thanks,

  • Ninja

Mass Assignment from ajax

I have an vue form component that i use for both showing and updating. I have to fetch data from server first. if i write

this.form=response.data

the form object get erased.
I have to do

this.form.attribute1=response.data.attribute1
etc..

There is no problem the attributes are few, but if there are many attributes is there a way i can do mass assignement ?

how to check for errors with specified keys

i want to be able to pass an array of keys to check if the error bag contains any of them and return true or key/value pair array. maybe something like the form.only() so we will have something like this form.errors.only()

Catching 500 errors

Sometimes the application will throw a 500 error. Is there a way to handle/catch/show those with this package?

Thanks :)

Quick question

I've been through the Laracasts' videos last week, and I really liked the work, so thanks for packaging this.

Quick question though, as I don't see this in the usage section: where exactly would you require the package exactly? My initial thought was that you'd probably make a reusable component out of this, but it seems like you didn't, and Jeffrey used the classes he made directly in a "master" js file.

So, say in a more traditional Laravel project, how do you envision this being used?

Would yourequire this package in app.js or bootstrap.js? Would you use the code in all of your component.vue files? Something else?

File Upload Array Validation

Has anybody got this to work with validation for file uploads when attaching multiple files. Maybe I'm just doing something wrong.

Pretty basic form:

<template>
    <form enctype="multipart/form-data">
        <div class="modal-card">
            <header class="modal-card-head">
                <p class="modal-card-title">New File</p>
            </header>
            <section class="modal-card-body">

                <div class="field">
                    <label class="label" for="files">Files</label>
                    <div class="control">
                        <input id="files"
                               type="file"
                               multiple
                               class="input"
                               :class="{'is-danger': form.errors.has('files')}"
                               name="files[]"
                               @change="handleFileUpload"
                               required>
                    </div>
                    <p class="help is-danger" v-show="form.errors.has('files')">
                        {{ form.errors.first('files') }}
                    </p>
                </div>

            </section>
            <footer class="modal-card-foot modal-card-foot-right">
                <div class="field is-grouped">
                    <p class="control">
                        <button class="button is-light" type="button" @click="$parent.close()">Cancel</button>
                    </p>
                    <p class="control">
                        <button type="submit" class="button is-primary" :class="{'is-loading': form.processing}" @click.prevent="save" :disabled="form.processing">
                            Save Changes
                        </button>
                    </p>
                </div>
            </footer>
        </div>
    </form>
</template>
<script>
    import Form from 'form-backend-validation';

    export default {
        props: ['id'],

        data() {
            return {
                form: new Form({
                    files: [],
                }),
            };
        },

        methods: {
            save() {
                console.log(this.form);
                this.form.post(`/client-files/${this.id}`)
                    .then(response => {
                        this.$emit('added', response);
                        this.$parent.close();
                    });
            },

            handleFileUpload($event) {
                this.form.files = $event.target.files || $event.dataTransfer.files;
            },
        },
    }
</script>

Then the backend is pretty basic too:

 public function store(Client $client, Request $request)
    {
//        $this->validate($request, [
//            'files'   => ['required', 'array'],
//            'files.*' => ['required', 'file'],
//        ]);

        $client
            ->addMultipleMediaFromRequest(['files'])
            ->each(function ($fileAdder) {
                $fileAdder->toMediaCollection('clients');
            });

        return response([], 200);
    }

Unfortunately validation fails every time, so I had to comment it out for now to make it work. Like I said, maybe I'm just doing something incorrectly here.

If anybody has gotten the form uploading working with validation, let me know. Thanks.

Cannot update data in view after put request because data gets reset after successful submission

I have a form with a single text field named content.
Let's say it's default value is "Taylor".
And then I type into the field and change it's value to "Jeffrey".
After a successful put request, I want to emit the updated value (which is Jeffrey) to the parent to reflect the change in the view.

onUpdateQuote() {

	// At this point in the code, the value of this.form.content is "Jeffrey"
	// since I typed into the form and changed it
	console.log('before ajax request: ' + this.form.content);

	this.form.put(appUrl.api('/quote/update/' + this.qt.id).withToken())
	.then(response => {

		// However, upon success, the value of this.form.content goes back to "Taylor"
		// I wish to send the updated value "Jeffrey" via $emit
		// but I can't because it has been reset
		console.log('after ajax request: ' + this.form.content);

		this.editing = false;
		this.$emit('quoteUpdated', {
			id: this.qt.id,
			content: this.form.content
		});
		// this.$store.commit('setAlert', response.message);
	})
	.catch(error => console.log(error));
}

Is this actually the intended behavior?

EDIT: I saw this in the code so I guess it was intended. What if you make it so that put requests don't execute a form reset? Are there any cases where it would cause problems?

onSuccess() {
	this.reset();
}

Add onUploadProgress config

It would be great if you could add a onUploadProgress feature. This feature will allow us to add a progress bar, and it is great for user experience if you are uploading large files.

The implementation could be solved like this (this example is from another form validation component):

submit(method, url, data = {}) {

        this.progress = 0;
        this.errors.clear();
        this.isPending = true;

        return new Promise((resolve, reject) => {
            axios[method.toLowerCase()](url, this.formData(data), this.config())
                .then(response => {
                    resolve(response.data);
                })
                .catch(error => {
                    this.handleError(error);
                    reject(error);
                })
                .then(() => this.isPending = false);
        });
    }

config() {
        return {
            onUploadProgress: progressEvent => {
                this.progress = Math.round((progressEvent.loaded * 100) / progressEvent.total);
            }
        }
    }

required field

Hello,
so for example we have a field Title. which is required...
When first we see the field, we want see it as untouched (no success/error state)

later when we write down the title. - it becomes success
but when we remove whole text from title - we want it become error.

how would you do that?

[BUG] Request is not handled by php when sending file by PUT method.

Hi folks!
Just to let you that I've found a "bug" due to the file upload. 😕

Actually this because of a php bug: if you send data in multipart/form-data, you have to do it by post.
It's an old heritage from times where the requests where made by html form.

see symfony/symfony#9226 for examples and links to explanations.

So if you try to send a form with a file with form.put method, php and symfony request will not handle it. I personally managed it by sending it via post and adding the laravel _method parameter to be considered as a PUT by Laravel.

I don't know if it's the same in Symfony and didn't try yet.

Maybe we should do something: add the _method automatically/don't convert in formdata if not post /just warn the user/etc

Imo we could warn the user in documentation (maybe with a link the _method tip for the Laravel users) and via a console error if (s)he try to send a file with an other method than post and just send the request without the file.

What are your thoughts about that?

Delete doesn't accept request body data

Delete doesn't accept request body data

The issue is related to axios, as I noticed when using this format of call, will not accept the body data

axios.delete(route, data);

but when using this format of call, it accepts the body data

axios({
method: 'delete',
data: data,
})

Add method hashasMultiple

Hi, it would be nice if there is method to get multiple fields errors at the same time, so if i have tabs i can mark tab with error.

Thanks

[Question] A good way to clear errors

First off, thanks for the good work in maintaining this package! 👍

In the laracasts video, jeffery was using @keydown as an example on the form to clear errors. However, this approach doesn't work with select inputs. I have the following scheme right now:

<template>
    <form @submit.prevent="onSubmit" @keydown="form.errors.clear($event.target.name)" @change="errClear($event.target.tagName, $event.target.name, $event.target.value)">
...
...
</template>

<script>
...
        methods: {
            // error clearing setup for SELECT type fields
            errClear(type, name, value) {
                if (type === 'SELECT') {
                    this.form.errors.clear(name);
                }
            }
        }
...
</script>

This almost works out correctly, except for the field defined with number inputs. If the up / down arrow buttons are used, the errors don't clear as it's not covered by either of the above two.

I tried @input event but that doesn't work until the field loses focus so it doesn't give the user a consistent behavior.

So the question is, what are you guys using? 😄

Add flexible request method

A lot of my form methods are re-used for post, put and patch

So with other libraries I like to do something like this:

        .request({
          method: form.id > 0 ? 'patch' : 'post',
          url: form.id > 0 ? this.api.update : this.api.add,
          data: form,
        })

Since this library doesn't have a request method I'm forced to do an unnecessary if/else or duplicate my method code. It would be nice if a flexible request method that receives the method name would be added. Axios has one as do many other libraries.

Please consider. Thanks!

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.