Vee-validate: password custom validation rule

Created on 23 Oct 2016  Â·  10Comments  Â·  Source: logaretm/vee-validate

Hi Logaretm,

I am trying to add password validation using a regex I found online and adding it as a custom rule. The idea is that one should have a password that is strong enough. However, I seem to get a problem adding the regex. I add the code example below.

Next, I tried something else which you can see in the second piece of code. This time there is no regex error, but there is an error in regards to attach() not being a function.

Help or hints are much appreciated.

All best,
Max

import { Validator } from 'vee-validate';

Validator.extend('verify_password', {
    getMessage: field => `The password must contain at least: 1 uppercase letter, 1 lowercase letter, 1 number, and one special character (E.g. , . _ & ? etc)`,
    validate: value => resolve({
        valid: ^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#\$%\^&\*])(?=.{8,}).test(value);
    });
});

Validator.attach('password', 'required|min:8|verify_password');
import { Validator } from 'vee-validate';

Validator.extend('verify_password', {
    getMessage: field => `The password must contain at least: 1 uppercase letter, 1 lowercase letter, 1 number, and one special character (E.g. , . _ & ? etc)`,
    validate: value => {
        var strongRegex = new RegExp("^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#\$%\^&\*])(?=.{8,})");
        return strongRegex.test(value);
    }
});
Validator.attach('password',  #'required|min:8|verify_password');

Most helpful comment

I figured it out. Use it as below

import VeeValidate from 'vee-validate';
Vue.use(VeeValidate);

VeeValidate.Validator.extend('verify_password', {
    getMessage: field => `The password must contain at least: 1 uppercase letter, 1 lowercase letter, 1 number, and one special character (E.g. , . _ & ? etc)`,
    validate: value => {
        var strongRegex = new RegExp("^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#\$%\^&\*])(?=.{8,})");
        return strongRegex.test(value);
    }
});

Then:
<input type="text" name="password" v-model="password" v-validate="'required|min:8|verify_password'" data-vv-as="New Password">

All 10 comments

attach is not a 'static` method, it is an instance method, so you have to create an instance first like this:

const validator = new Validator();
// or
const validator = Validator.create();

then you can call attach normally:

validator.attach('password', 'required|min:8|verify_password'); // this is the instance.

Note that attaching fields does not attach the input event listeners, meaning you also need to do this:

// 1 - extend and add custom rule.
// 2 - Attach the field.

const input = document.querySelector(`...`); // select the input from the DOM or use Vue's refs.
input.addEventListener('input', function () {
   validator.validate('password', this.value); // this here is the el since I did not use arrow funcs.
});

in the future I might add the ability to pass the element and the validator should attach whatever events necessary.

Hi again,

Thanks for your replay! I actually still continue to get the error: Uncaught TypeError: validator is not a function. The code is below:

All best,
Max

    import { Validator } from 'vee-validate';

    Validator.extend('verify_password', {
        getMessage: field => `The password must contain at least: 1 uppercase letter, 1 lowercase letter, 1 number, and one special character (E.g. , . _ & ? etc)`,
        validate: value => {
            var strongRegex = new RegExp("^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#\$%\^&\*])(?=.{8,})");
            return strongRegex.test(value);
        }
    });

    Validator.updateDictionary(dictionary);

    // with either of the two lines I get the same error.
    // const validator = new Validator();
    let validator = new Validator();

    validator.attach('password', 'required|min:8|verify_password');

That's weird, I've setup a small example for you here I'm using both the directive and the custom logic we were talking about here, I hope that helps.

@logaretm thanks again for your reply! I will check it later in the day. I can see some small differences in what I did, so I am guessing I will now be able to implement things correctly.

All best,
Max

Hi again,

That worked now :-)

All best,
Max

Hi,
the example link can not work now

All best

Yeah the example link has been moved.

Please provide the example again.

I figured it out. Use it as below

import VeeValidate from 'vee-validate';
Vue.use(VeeValidate);

VeeValidate.Validator.extend('verify_password', {
    getMessage: field => `The password must contain at least: 1 uppercase letter, 1 lowercase letter, 1 number, and one special character (E.g. , . _ & ? etc)`,
    validate: value => {
        var strongRegex = new RegExp("^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#\$%\^&\*])(?=.{8,})");
        return strongRegex.test(value);
    }
});

Then:
<input type="text" name="password" v-model="password" v-validate="'required|min:8|verify_password'" data-vv-as="New Password">

Hmm the documentation is unclear, but i solved it this way:

app.js

new Vue({
    el: '#root',
    created() {
        this.$validator.extend('emailAlreadyExists',{
    getMessage: field => field + ' already exists.',
    validate: value => {
        return new Promise(resolve => {
            axios.get('/skills')
                .then(function (response) {
                    console.log(response.data[0]);
                    resolve({
                        valid: response.data[0],
                        data: value !== 'trigger' ? undefined : {message: 'Not this value'}
                    });
                })
                .catch(function (error) {
                    // handle error
                    console.log(error);
                })
                .then(function () {
                    // always executed
                });

        });
    }
});
    }
});

And html
<input type="text" v-validate="'required|email|emailAlreadyExists'" v-bind:class="[errors.first('email') ? 'registration_error' : '', 'form-control ']" name="email"/>
it seems like you have to register the validator in the created method

Was this page helpful?
0 / 5 - 0 ratings