Last active
October 27, 2018 02:08
-
-
Save bseib/30570a7c0d5e5a1499fa57ce09fa2f2b to your computer and use it in GitHub Desktop.
VueJS directive to inject 'is-invalid' class on element based on a value
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Register a global custom directive called `v-invalid` | |
Vue.directive('invalid', (function() { | |
var setInvalidClass = function(el, isInvalid) { | |
var isActWhenUntouched = el['_isActWhenUntouched']; | |
var isTouched = el['_isTouched']; | |
if ( isActWhenUntouched || isTouched ) { | |
if ( isInvalid ) { | |
el.classList.add('is-invalid'); | |
} | |
else { | |
el.classList.remove('is-invalid'); | |
} | |
} | |
}; | |
var inputListener = function(e) { | |
//console.log("touch happened."); | |
e.target['_isTouched'] = true; | |
e.target.classList.add('is-touched'); | |
}; | |
return { | |
inserted: function (el, binding) { | |
//console.log("inserted-binding-value="+binding.value); | |
var isActWhenUntouched = !! binding.modifiers.untouched; | |
el['_isActWhenUntouched'] = isActWhenUntouched; | |
setInvalidClass(el, binding.value); | |
el.addEventListener('input', inputListener); | |
}, | |
componentUpdated: function(el, binding) { | |
//console.log("componentUpdated-binding-value="+binding.value); | |
setInvalidClass(el, binding.value); | |
}, | |
unbind: function(el, binding) { | |
//console.log("ubind-binding-value="+binding.value); | |
el.removeEventListener('input', inputListener); | |
}, | |
} | |
})()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is intended to be used with Bootstrap, where
.is-invalid
class will mark an input field invalid.The element will not be given the
is-invalid
class until it has been "touched", i.e., received an input event. If you wish to apply theis-invalid
class immediately, then use theuntouched
modifier on the directive: