Search code examples
javascriptvue.jsvuejs2v-modelvuelidate

Vue js vuelidate custom validation


I'm creating basic stock management system. In there, the invoicing I want to validate, the price user enter must be greater than or equal to the minimum selling price. I use vuelidate package for the validations.

Any clue how to achieve this using vuelidate


Solution

  • You could use a custom validator called price_greater as follow :

       const price_greater = (value, vm) => (value >= vm.min_price);
    

    and add it to validations property :

    validations: {
        user_price: {
             required,
             price_greater
           }
    }
    

    check the following example:

    Vue.use(window.vuelidate.default)
    const {
      required
    } = window.validators;
    const price_greater =
      (value, vm) => (value >= vm.min_price);
    new Vue({
      el: "#app",
      data() {
        return {
          min_price: 455,
          user_price: 0,
          respectMinPrice: false
        }
      },
      methods: {
        status(validation) {
          return {
            error: validation.$error,
            dirty: validation.$dirty
          }
        }
      },
    
      validations: {
    
        user_price: {
          required,
          price_greater
        }
      }
    })
    #app {
      font-family: "Avenir", Helvetica, Arial, sans-serif;
      -webkit-font-smoothing: antialiased;
      -moz-osx-font-smoothing: grayscale;
      text-align: center;
      color: #2c3e50;
      margin-top: 60px;
    }
    
    input {
      border: 1px solid silver;
      border-radius: 4px;
      background: white;
      padding: 5px 10px;
    }
    
    .dirty {
      border-color: #5A5;
      background: #EFE;
    }
    
    .dirty:focus {
      outline-color: #8E8;
    }
    
    .error {
      border-color: red;
      background: #FDD;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.2.1/vue.min.js"></script>
    <script src="https://unpkg.com/vuelidate/dist/vuelidate.min.js"></script>
    <script src="https://unpkg.com/vuelidate/dist/validators.min.js"></script>
    
    
    
    <div id="app">
      <input v-model="$v.user_price.$model" placeholder="user_price" type="number" :class="status($v.user_price)">
    
      <p class="error" v-show="respectMinPrice">user price must be greater or equal to min selling price</p>
    </div>

    if you're working with single file component check this solution