Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VeeValidate multiple password constraints

I'm wondering if it's possible to have multiple password requirements passed to VeeValidate in order to display which requirements a user is missing.

For instance, if we require that a user's password should have at least one uppercase letter and at least one number and be at least 5 characters long, and the user types in "a1bb", we'd like to be able to display two error messages; one associated with the length requirement not being met and one related to the uppercase requirement not being met.

Ultimately, we'd like to be able to do something like this: enter image description here

Would that be possible with VeeValidate? Or are there any examples of a similar approach?

like image 815
user2909019 Avatar asked Mar 14 '19 19:03

user2909019


Video Answer


1 Answers

VeeValidate allows you to display multiple errors fields but you need to disable the fastExist config option first:

VeeValidate only generates one message per field by default as it uses a fast-exit strategy when running the validation pipeline. [...] To disable this behavior you may want to configure the fastExit option in VeeValidate's config or use the continues modifier. (source)


For the rules you want to apply to password, you can use the existing min rule for the minimum length.

For the other rules (check upcase, lowercase, special char and digit), it's about regex check. VeeValidate actually provides a regex rule but in your case you need multiple ones.

So you need to define custom rules. I put some examples in the snippet below in the created hook but you also can define them globally.


In my example, I create a method to return a css class error by checking the errors by rule name.(source)
Now the style is yours.

const config = {
  fastExit: false
}
Vue.use(VeeValidate, config)

new Vue({
  el: "#app",
  data() {
    return { password: '' }
  },
  created() {
    this.$validator.extend('upCase', {
      getMessage: () => "One uppercase character",
      validate: value => value.match(/[A-Z]/g) !== null
    })
    this.$validator.extend('number', {
      getMessage: () => "One number",
      validate: value => value.match(/[0-9]/g) !== null
    })
  },
  methods: {
    errorClass(rule) {
      return {
        'error': this.errors.firstByRule('password', rule)
      }
    }
  }
})
li {
  color: #B1B1B1;
}
li.error {
  color: #262626;
}
<script src="https://unpkg.com/[email protected]/dist/vue.min.js"></script>
<script src="https://unpkg.com/[email protected]/dist/vee-validate.js"></script>
<div id="app">
  <input type="text" v-validate="'min:8|number|upCase'" name="password" >
  <ul>
    <li :class="errorClass('upCase')">One uppercase character</li>
    <li :class="errorClass('number')">One number</li>
    <li :class="errorClass('min')">8 characters minimum</li>
  </ul>
</div>
like image 127
Sovalina Avatar answered Oct 01 '22 05:10

Sovalina