AfikDeri / v-credit-card

Beautiful credit card form component for vueJS
MIT License
63 stars 27 forks source link

How do you add validations rules? #5

Closed borgrodrick closed 4 years ago

borgrodrick commented 5 years ago

How do you go about adding custom validations if using as a component ?

AfikDeri commented 5 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>
borgrodrick commented 4 years ago

Thanks a lot for the sample, is it possible to add the validation messages inline in the component?

AfikDeri commented 4 years ago

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.