简体   繁体   English

仅接受十六进制输入

[英]Accept hex only input

I am trying to create an input box that only accepts Hex characters [A-Fa-f0-9] .我正在尝试创建一个只接受十六进制字符[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需要限制实际用户输入(因此不允许输入/按键/粘贴 A-Fa-f0-9 以外的字符
    • I know this can be done through keyup/keydown/onchange event, but I need this to be enabled globally, more elegant solution我知道这可以通过 keyup/keydown/onchange 事件来完成,但我需要在全球范围内启用它,更优雅的解决方案
  • 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.另一个选项是输入pattern ,但这仍然允许用户输入“无效”字符,稍后将显示验证失败。

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):如果可能的话有一个 vue 指令(假设q-input是我的组件):
<q-input v-hex>

So I created this vue directive that removes all non-hex characters and converts letters it to uppercase:所以我创建了这个 vue 指令,它删除所有非十六进制字符并将字母转换为大写:

Vue.directive('hex', {
  update: function (el, binding) {
        console.log('Input ' + binding.value)
    
    var newVal = binding.value.replace(/[^a-fA-F0-9\n\r]+/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 ).但它不会更新在 v-model 中传递的参数(包含binding.value的参数)。

Here is my fiddle: https://jsfiddle.net/keechan/nade9cy0/3/这是我的小提琴: https://jsfiddle.net/keechan/nade9cy0/3/

Sample input -> expected output:样本输入 -> 预期 output:

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

How can I update its respective v-model parameter?如何更新其各自的 v-model 参数? Please note that this directive will be used globally so no hardcoding anywhere.请注意,该指令将在全球范围内使用,因此在任何地方都没有硬编码。

Anyone help?有人帮忙吗? Thanks谢谢

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

https://jsfiddle.net/6bw0zvdm/ https://jsfiddle.net/6bw0zvdm/

Quasar uses some deferred model update magic, thus using specific private method __emitValue ( source ) Quasar 使用了一些延迟的 model 更新魔法,因此使用了特定的私有方法__emitValue ( source )

By the way, you don't need to specify directive expression ( "txt" ), v-hexonly will work.顺便说一句,您不需要指定指令表达式( "txt" ), v-hexonly将起作用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM