Vuelidate Required If example

by timbarclay

HTML

<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">
  
  <label>
     <input v-model="directory" />
     <div v-if="$v.directory.$invalid">Doesn't exist</div>
  </label>
  <button type="button" @click="recheck">
    Recheck
  </button>

  <pre>{{ $v }}</pre>
</div>

CSS

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;
}

.error:focus {
  outline-color: #F99;
}

Babel + JSX

Vue.use(window.vuelidate.default)

let exists = false

// Simulates an API call. Just alternates returning true or false
function checkExists () {
	return new Promise(resolve => {
    setTimeout(() => {
      this.exists = !this.exists
      resolve(this.exists)
    }, 200)
  })
}

new Vue({
	el: "#app",
  data: {
    directory: '',
  },
  validations: {
    directory: {
      exists(value) {
        return checkExists().then(exists => exists)
      }
    }
  },
  methods: {
  	// This should re-run the exists check
    recheck() {
      this.$v.directory.$touch()
    }
  }
})