Vee-validate : how to attach several validation rules after object constructed

Dolche picture Dolche · Apr 26, 2018 · Viewed 7.1k times · Source

I'm a newbie in Vue.js development.

Using Vee-validate, I want to put validation rules "required" and "regex" (for example, telphone num should be required && \d{11}).

I read the official documentation carefully.

However, I can't figure out how to put two conditions including regex expression inside " created() " of Vue instance.

The below works:

this.$validator.attach({ name: "tel", rules: "required" });

but this does not work:

this.$validator.attach({ 
  name: "tel", 
  rules: "{ 
    required: true , regex: /\d{11}/ 
  }'" 
});

How can I enable more than one condition?

Answer

Derek Fulginiti picture Derek Fulginiti · Apr 26, 2018

I prefer using the directive version myself. Once you import VeeValidate into your component, you have access to all of the built-in validation via v-validate and can chain them together using the pipe | operator:

<template>
    <input name="email" type="text" v-model="emailData" v-validate="'required|email'">
    <button @click="submit()"></button>
</template>

<script>
    import VeeValidate from 'vee-validate'; //wherever your plugin is stored
    data() {
        return {
            emailData: null,
        },
    },
    methods: {
        // call this method upon form submission, this will validate all fields using the specified validation
        submit() {
            this.$validator.validateAll().then((result) => {
                if (result) {
                    // form/input(s) passed validation. Do something
                }
            });
    }
</script>

If you'd like to accomplish this without using directives, the following should work:

import { Validator } from 'vee-validate';
const validator = new Validator();
const expressions = {
    required: true,
    regex:    /\d{11}/
};
validator.attach({ name: 'tel', rules: expression });
// continue with validator.validate() etc...