Solution 1 :

Vue.directive('hexonly', {
    bind(el, binding, vnode) {
        const vm = vnode.componentInstance;
        el.__unbindHexonly = vm.$watch('value', value => {
            vm.__emitValue(value.replace(/[^a-fA-F0-9nr]+/g, '').toUpperCase());
        }, { immediate: true });
    unbind(el) {
        el.__unbindHexonly && el.__unbindHexonly();

Quasar uses some deferred model update magic, thus using specific private method __emitValue (source)

By the way, you don’t need to specify directive expression ("txt"), v-hexonly will work.

Problem :

I am trying to create an input box that only accepts Hex characters [A-Fa-f0-9].

I know there are a lot of options but have found none that ticks all my checkboxes.

  • Need to restrict actual user input (so characters other than A-Fa-f0-9 will NOT be allowed entry/keypress/paste
    • I know this can be done through keyup/keydown/onchange event, but I need this to be enabled globally, more elegant solution
  • Another option is the input pattern, but this still allows user entry of ‘invalid’ characters, will just display later on that the validation has failed.

My thoughts:

  • Top choice: If it is possible to extend the input type:
<input type="hex">
  • If possible to have a vue directive for this (supposing q-input is my component):
<q-input v-hex>

So I created this vue directive that removes all non-hex characters and converts letters it to uppercase:

Vue.directive('hex', {
  update: function (el, binding) {
        console.log('Input ' + binding.value)
    var newVal = binding.value.replace(/[^a-fA-F0-9nr]+/g, '')
      console.log('New Hex Only Val = ' + newVal.toUpperCase())

    binding.value = newVal

But it doesn’t update the parameter passed in the v-model (parameter holding the binding.value).

Here is my fiddle:

Sample input -> expected output:

  • 123abc -> 123ABC
  • 12hf23dn -> 12F23D

How can I update its respective v-model parameter? Please note that this directive will be used globally so no hardcoding anywhere.

Anyone help?


Comment posted by noobHere

yes, if you are going to repeat this input.. instead of using

Comment posted by

Haven’t created a custom vue-directive before but it seems they always start with

Comment posted by kzaiwo

@Rie ah yes, i have updated my description. But on the fiddle link, it is v-hex.. but still cant make it work

Comment posted by…

Hmmm. this seems to be more of a quasar-specific issue then. I mean, you did tag quasar (I just didn’t see it, my bad). You could try to extend the quasar component using