简体   繁体   English

如何设置用户不能在第一个数字中输入数字0?

[英]How do I set the user can not enter the number 0 in the first number?

I try like this:我尝试这样:

   <v-text-field
      type="number"
       @keyup="handler(text)"
        v-model="text"
    >

Demo and full code like this: https://codepen.io/positivethinking639/pen/yLeoppa演示和完整代码如下: https://codepen.io/positivethinking639/pen/yLeoppa

But this code has not worked perfectly.但是这段代码并没有完美运行。 If I enter 852 .如果我输入852 Then I move the cursor to the right of the number 8 and enter the number 0 , it can.然后我把 cursor 移到数字8的右边,输入数字0 ,就可以了。 So this code isn't perfect所以这段代码并不完美

How can I solve this problem?我怎么解决这个问题?

Using a regex:使用正则表达式:

new Vue({
  el: '#app',
  vuetify: new Vuetify(),
  data: () => ({
    text: null
  }),
  methods: {
    handler(val){
        this.text = val.replace(/^[^1-9]+/, '')
    }
  }
})

Demo You are looking directly whole enter. Demo你直接看整个进入。 just check first letter只需检查第一个字母

if(val.substr(0,1)==="0"){
    this.text=val.slice(1);
}

If you want the preserve the string, like if someone types 852 and then you add the 0 in front, and you want it to change back to 852 rather than null.如果您想要保留字符串,例如有人键入 852,然后您在前面添加 0,并且您希望它改回 852 而不是 null。

Like change 0852 -> 852 if the zero was added later.如果稍后添加零,就像更改0852 -> 852一样。

Then you should update your handler function然后你应该更新你的处理程序 function

handler(val){
      if(val==="0"){
         this.text=null;
      }
      if(val[0] === "0"){
        this.text = this.text.substr(1);
      }
    }

You can check if the first char is "0" like this:您可以像这样检查第一个字符是否为“0”:

 if(val[0] === "0") {
    this.text = null;
 }

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

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