2

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?

2
  • Does it print some error message or something? Did you try mounted hook instead? Apr 26, 2018 at 21:05
  • 1
    Remove the double quotes around the rules object. Should be: validator.attach({ name: "tel", rules: { required: true, regex: /\d{11}/ }}); Apr 27, 2018 at 0:54

1 Answer 1

2

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...
1
  • rules: "{ required: true , regex: /\d{11}/ }'" is syntax error which says "unexpected token : "
    – Dolche
    Apr 27, 2018 at 0:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.