You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue.js输入框数字限制失效:仍可输入字符,切换字段才生效

Fix Real-Time Numeric Input Restriction for Your Vue Textbox

Looks like your current setup only validates input when you switch fields (on blur) instead of blocking invalid characters as you type. Let's fix this by refining your isNumber event handler to properly intercept non-numeric keystrokes in real time.

What's causing the issue:

  • Your v-validate decimal rule runs on field blur by default, so it only cleans up invalid input after you leave the field.
  • The existing isNumber method likely isn't properly blocking non-numeric characters (like letters) or handling decimal points correctly during keypress.

Step 1: Update the isNumber Method

Replace your current isNumber function with this robust version that blocks invalid input immediately:

methods: {
  isNumber(event) {
    const charCode = event.which || event.keyCode;
    // Allow digits, backspace, delete, arrow keys, and a single decimal point
    const isDigit = charCode >= 48 && charCode <= 57;
    const isAllowedControl = charCode === 8 || charCode === 46 || (charCode >= 37 && charCode <= 40);
    const hasExistingDecimal = event.target.value.includes('.');
    const isDecimalKey = charCode === 46;

    // Block input if it's not a digit/allowed control, or if we're adding a second decimal
    if (!isDigit && !isAllowedControl || (isDecimalKey && hasExistingDecimal)) {
      event.preventDefault();
    }
  }
}

Step 2: Verify Event Binding (For Custom Components)

If <ui-textbox> is a custom component, make sure it forwards the native keypress event from its internal <input> to the parent. Inside the ui-textbox component:

<template>
  <div class="textbox-wrapper">
    <label>{{ label }}</label>
    <input 
      :value="value"
      @input="$emit('input', $event.target.value)"
      @keypress="$emit('keypress', $event)" <!-- Forward the keypress event -->
      :class="{ invalid: invalid }"
    >
    <span class="error" v-if="error">{{ error }}</span>
  </div>
</template>

Why this works:

  • This handler blocks any keystroke that isn't a number, a control key (backspace, arrows), or a single decimal point—so invalid characters never make it into the input.
  • The v-validate rule still acts as a safety net for edge cases (like pasting invalid text), but the keypress handler takes care of real-time prevention.

内容的提问来源于stack exchange,提问作者user6632933

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 06:48:27