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-validatedecimalrule runs on field blur by default, so it only cleans up invalid input after you leave the field. - The existing
isNumbermethod 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-validaterule 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
相关产品推荐
相关产品推荐

