Closed borgrodrick closed 4 years ago
You should wrap this component with your own component that has it's own data. then you could validate the data before submitting the form and show the error.
Here is an example:
<template>
<div class="Credit-card-form">
<p class="error" v-if="validationError" v-text="validationError"></p>
<VCreditCard @change="creditInfoChanged"/>
<button @click="submit">PAY</button>
</div>
</template>
<script>
import VCreditCard from 'v-credit-card';
export default {
data() {
return {
validationError: null
card: {
name: '',
cardNumber: '',
expiration: '',
security: ''
}
};
},
methods: {
creditInfoChanged(values) {
for (const key in values) {
this.card[key] = values[key];
}
},
submit() {
// Validate the this.$data.card object with any third party or your own validation library.
const error = this.validateSomehow(this.$data.card);
if (error) {
this.validationError = error;
return;
}
// if valid:
axios.post('/payment', this.$data.card)
.then(res => console.log(res.data))
.error(error => {
this.validationError = error.response.data;
})
}
},
components: {
VCreditCard
}
}
</script>
Thanks a lot for the sample, is it possible to add the validation messages inline in the component?
At the moment this is not possible, you can definitely send a PR if you have an idea. I would probably go with named slots for each field or a single slot in the component body. not sure exactly but it could be a nice solution.
Anyway, I'm closing the issue. thanks.
How do you go about adding custom validations if using as a component ?