Vee Validate 3 catch errors on form submit - vue.js

How do i catch if form submit fails in vee-validate? I have the following component
<template>
<ValidationObserver tag='div' class='bg-white pt-6 pb-6 mb-4' v-slot='{ handleSubmit }'>
<form
#submit.prevent='handleSubmit(onSubmit)'
class='mx-auto rounded-lg overflow-hidden pt-6 pb-6 space-y-10'
:class="{'is-loading' : isLoading}"
>
<div class='flex flex-wrap -mx-3 mb-6'>
<div class='w-full md:w-3/12 px-3 mb-6 md:mb-5'>
<ValidationProvider v-slot='{ classes, errors }' rules='required' name='Anrede'>
<CustomSelect :options='gender'
placeholder='Anrede *'
v-model='form.gender'
:class="classes"
/>
<span class='text-mb-error font-medium text-sm italic'>{{ errors[0] }}</span>
</ValidationProvider>
</div>
</div>
<div class='block'>
<button
class='bg-secondary hover:bg-secondary-200 text-white py-3 px-4 w-full mt-5 focus:outline-none'
type='submit'
>
Registrieren
</button>
</div>
</form>
</ValidationObserver>
</template>
as method I have the following function
onSubmit () {
alert()
console.log(this.$refs.observer)
this.$emit('onSendRegistration', this.form)
}
which works fine if form is valid but if it fails never gets executed. Where can I catch if form validation fails?

As per the documentation:
[handleSubmit] calls validation like validate and mutates provider's state, accepts a callback to be run only if the validation is successful.
So to run a callback in the case of an error in validation you would have to trigger the validation programmatically using a ref in the ValidationObserver.
Your opening ValidationObserver tag would now look like this:
...
<ValidationObserver tag='div' class='bg-white pt-6 pb-6 mb-4' ref='form'>
...
Your opening form tag should be now like this:
...
<form
#submit.prevent='onSubmit'
class='mx-auto rounded-lg overflow-hidden pt-6 pb-6 space-y-10'
:class="{'is-loading' : isLoading}"
>
...
And your onSubmit method should be something like this:
onSubmit () {
this.$refs.form.validate().then(success => {
if (!success) {
// run your error code here
}
alert('Form has been submitted!');
});
}
Besides this programmatic approach there's no equivalent to handleSubmit for running a callback function after an invalid form submission.
Check the docs for more info about the programmatic access with $refs.

Related

Cannot execute scoped slot and function in the same event Vue

I have the following code which uses this VueTailwind package:
<t-dropdown>
<div
slot="trigger"
slot-scope="{mousedownHandler, focusHandler, blurHandler, keydownHandler}"
>
<button
id="reseller-menu"
aria-label="User menu"
aria-haspopup="true"
#mousedown="mousedownHandler"
#focus="focusHandler"
#blur="blurHandler"
#keydown="keydownHandler"
>
{{ $page.props.auth.user.reseller.name }}
<icon icon="chevron-down" class-name="ml-2" />
</button>
</div>
<div slot-scope="{ blurHandler }">
<span v-for="user in users" :key="reseller.id" role="menuitem" class="block px-6 cursor-pointer py-2 hover:bg-indigo-500 hover:text-white"
#click="changeUser(user.id); blurHandler">{{ user.name }}</span>
</div>
</t-dropdown>
However, the blurHandler is not executed whenever the changeUser(user.id) method (a method in the parent component which seems to execute fine) is added to the #click event. The only way I was able to solve this issue was to use two different events such as the following:
<span v-for="user in users" :key="reseller.id" role="menuitem" class="block px-6 cursor-pointer py-2 hover:bg-indigo-500 hover:text-white"
#click="changeUser(user.id)" #mouseup="blurHandler">{{ user.name }}</span>
How can I use both in the same event since this doesn't seem to work in this case?
When the v-on value is a function reference, the template compiler transforms it into a function call, passing the event argument:
<button #click="functionRef">
<!-- ...is transformed into: -->
<button #click="functionRef($event)">
But when the v-on value is an expression, the template compiler wraps it in a function:
<button #click="onClick(); functionRef">
<!-- ...is transformed into: -->
<button #click="() => { onClick(); functionRef; }">
Notice functionRef; is not a function call, and effectively does nothing. To actually invoke the function in that expression, add the parentheses to make it a call:
<button #click="onClick(); functionRef()">
So your markup should be:
<div slot-scope="{ blurHandler }">
<span v-for="user in users" ⋯ 👇
#click="changeUser(user.id); blurHandler()">
{{ user.name }}
</span>
</div>
Also note slot-scope has been deprecated for v-slot, as of 2.6.0.

VueJS - How to Enable/Disable a specific input in a v-for loop

I need to enable/disable specific inputs on button click.
My problem here is when I click my button, ALL the inputs enable/disable I am having a hard time targeting a single one.
I use props “articles” which returns the “id”, “title” and “body” of my articles.
<div v-for="(article, index) in articles" v-bind:key="article.id">
<div class="flex">
<div class="flex-1 px-2 py-2">
<input
v-model="article.title"
type="text"
:disabled="isDiabled"
class="w-full disabled:opacity-75 bg-gray-300 focus:bg-white"
/>
</div>
<div class="flex-1 px-2 py-2">
<input
v-model="article.body"
type="text"
:disabled="isDiabled"
class="w-full disabled:opacity-75 bg-gray-300 focus:bg-white"
/>
</div>
<div class="px-2 py-2">
<button
class="px-2 py-2 border-gray-400 bg-gray-800 rounded text-white hover:border-gray-300 items-end"
#click="enableEdit"
>
Edit
</button>
</div>
</div>
</div>
<script>
export default {
props: ["articles"],
data() {
return {
isDiabled: true,
};
},
methods: {
enableEdit() {
this.isDiabled = false;
},
},
};
</script>
Every article has his own button and I want only the two inputs of the button that is clicked to be enabled/disabled and not all of them.
As being pointed you need to add also that property to your articles... of course you don't need to do this in the database, still using it as a property you need also to emit this change of the flag to the parent.
You could also use a local version of the articles where you add also this isDisabled property, you fill this new variable at the creation of the component based of course on the property you received from the parent,
created(){
this.local_articles = this.articles.map(e => {
return {...e, isDisabled: true} }
)
},
this way you don't need to propagate nothing to the parent as you can handle all internally.
This fiddle gives a solution to your problem.
Make a boolean property for each article, then change the binding of disabled to that property.

Vee Validate 3.0 custom classes not applied

From the docs, I think I need to use configure to add custom classes to my validated fields, but I can't get it to work.
This is what I have so far...
import { extend, configure, localize } from 'vee-validate'
import { required, min, max } from 'vee-validate/dist/rules'
import en from 'vee-validate/dist/locale/en.json'
// Install rules
extend('required', required)
extend('min', min)
extend('max', max)
// Install classes
configure({
classes: {
valid: 'is-valid',
invalid: 'is-invalid'
}
})
// Install messages
localize({
en
})
And in my view....
<ValidationObserver ref="observer" v-slot="{ invalid }" tag="form" #submit.prevent="checkRef()">
<div class="form-group">
<label for="reference">Reference</label>
<ValidationProvider rules="required|max:20" name="reference" v-slot="{ errors }">
<input maxlength="20" name="reference" v-model="ref" id="reference" class="form-control"/>
<span class="warning">{{ errors[0] }}</span>
</ValidationProvider>
</div>
<button #click="checkRef" class="btn btn-primary app-button">Check Reference</button>
</ValidationObserver>
When I click the button, I see the error message but I don't get the 'in-invalid' class applied to my field.
What am I doing wrong?
VeeValidate does not apply the classes automatically anymore, since v3 you now must bind it yourself. Like errors you can extract classes from the slot props and apply it to your input:
<ValidationProvider rules="required|max:20" name="reference" v-slot="{ errors, classes }">
<input maxlength="20" name="reference" v-model="ref" id="reference" class="form-control" :class="classes" />
<span class="warning">{{ errors[0] }}</span>
</ValidationProvider>

Test a form which used veevalidate on that form

i using vee-validate version 3.0.11 for validate my form like below
<validation-observer v-slot="{ invalid }" slim>
<validation-provider rules="required" v-slot="{ errors, dirty, invalid}" slim>
<div class="form-group">
<label class="sr-only" for="txtUsername"></label>
<input
autocomplete="off"
id="txtUsername"
name="username"
type="text"
class="form-control txtUsername"
placeholder="Email or Username"
v-model="username"
v-bind:class="{ 'is-invalid': invalid && dirty,'is-valid': !invalid }" />
</div>
</validation-provider>
<validation-provider rules="required" v-slot="{ errors, dirty, invalid}" slim>
<div class="form-group">
<label class="sr-only" for="txtPassword"></label>
<input
id="txtPassword"
name="password"
type="password"
class="form-control"
placeholder="Password"
v-model="password"
v-bind:class="{ 'is-invalid': invalid && dirty,'is-valid': !invalid }" />
</div>
</validation-provider>
<div >
<button
type="button"
name="login"
class="btn btn-primary"
v-on:click="doLogin()"
:disabled="invalid">
Login
</button>
</div>
</validation-observer>
and i wrote some test with chai and mocha
in my test i need to find the button
but when i using find method for find button all html tag between validation-observer tag is not loaded in my wrapper.
my test code is:
// i change it to shallowMount to mount but problem is exist,
// mount does not render any thing between validation-observer tag
const wrapper = mount(LoginView, { sync: false });
describe('Login.vue', () => {
it('some text, () => {
console.log(wrapper.html());
// my log include all of tag except tags between the validation-observer tag
});
});
can some one tell me how i can find my button by using warraper.find(), please?
You are trying to shallow mount a component that needs to be mounted in order to render its children. If you want to ignore ValidationProvider all together you can provide a fake one as shown below.
ContactForm.vue
<template>
<div>
<ValidationProvider rules="required" name="input" v-slot="{ errors }">
<p :style="{color: 'red'}">To be, or not to be</p>
<input type="text" v-model="value">
<span id="error">{{ errors[0] }}</span>
</ValidationProvider>
</div>
</template>
<script>
import { ValidationProvider } from "vee-validate";
export default {
name: "ContactForm",
components: {
ValidationProvider
},
data: () => ({
value: ""
})
};
</script>
ContactForm.test.js
import { shallowMount, createLocalVue } from "#vue/test-utils";
import ContactForm from "./ContactForm";
import FakeValidationProvider from "./FakeValidationProvider";
test("Test shallow mount renders what's inside validation provider", async () => {
const localVue = createLocalVue();
var wrapper = shallowMount(ContactForm, {
stubs: {
ValidationProvider: FakeValidationProvider
},
localVue
});
expect(wrapper.text()).toContain("To be, or not to be");
});
FakeValidationProvider.vue
<template>
<div v-bind="{ ...$props, ...$attrs }">
<slot :errors="errors"></slot>
</div>
</template>
<script>
export default {
name: "FakeValidationProvider",
data() {
return {
errors: []
};
}
};
</script>
Feel free to extend the slot with any other parameters you need besides errors. If you want to make those parameters dynamic as well, check out this article on rendering slots

vue js navigate to url with question mark

my Vue js project login template click button it redirects to like this
http://localhost:8080/#/login to http://localhost:8080/?#/login
both Url show interface.
1st Url not set the local storage variable 'token'.
2nd Url is set the local storage variable 'token'.
how to solve it?
Login.vue
<template>
<div class="row col-sm-12">
<form>
<div class="form-group">
<label>Email address:</label>
<input type="email" class="form-control" v-model="email">
</div>
<div class="form-group">
<label>Password:</label>
<input type="password" class="form-control" v-model="password">
</div>
<div class="checkbox">
<label><input type="checkbox"> Remember me</label>
</div>
<button #click="login" type="submit" class="btn btn-success">Submit</button>
</form>
</div>
</template>
<script>
export default{
data(){
return{
email:'',
password:''
}
},
methods: {
login(){
var data = {
email:this.email,
password:this.password
}
this.$http.post("api/auth/login",data)
.then(response => {
this.$auth.setToken(response.body.token)
// console.log(response)
})
}
}
}
</script>
The form is getting submitted as the button you have provided in the form has type="submit" which is the default behaviour of a button present inside form even if you do not add the attribute type="button"
So replace the type submit to button o prevent form submission like this:
<button #click="login" type="button" class="btn btn-success">Submit</button>
I just faced the same issue, and the provided solution did not worked for me (Vue 2.5.17).
I had to add a modifier to the #click event to prevent the default behavior:
<button class="btn btn-primary" #click.prevent="login">Login</button>
Changing the button type to button, you disable default form behaviour, like pressing enter and release submit event.
Just add a modifier to the #submit or #reset event to prevent default behaviour:
<b-form #submit.prevent="onSubmit" #reset.prevent="onReset">
In order to keep the default behaviour of submitting the form using the "Enter" key on the keyboard as well, another solution is:
to keep the type = 'submit' on the button
handle the event parameter on the callback and process it with event.preventDefault(); like that:
login(event){
event.preventDefault()
var data = {
email:this.email,
password:this.password
}
...
}
Event.preventDefault() will prevent the default behaviour which is here to submit the form on the current url with the issue we are dealing with here.
See https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault