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

Vuetify v-text-field数字校验问题:空值不应触发错误

Fixing Vuetify v-text-field Validation: Allow Empty Values + Only Numeric Inputs

Got it, let's sort out this validation issue for your Vuetify text field. The problem with your current rule is that empty strings fail the ^\d+$ regex check, which triggers the error message even when the user clears the field. We'll adjust the rule to skip validation for empty values while enforcing numeric-only input when there's content.

Updated Validation Rule

Replace your existing integerValueCheck with this:

integerValueCheck: [
  v => !v || /^\d+$/.test(v) || 'Nur Zahlen erlaubt'
]

How It Works

  • !v: This checks if the value is empty (empty string, null, or undefined). If true, validation passes immediately—no error shows up when the field is cleared.
  • /^\d+$/.test(v): For non-empty values, this ensures the input is made only of digits (0-9). Any characters like +, -, ., , will fail this check and trigger your error message right away.
  • The fallback string 'Nur Zahlen erlaubt' displays when the input is non-empty and not purely numeric.

Example Usage in Your Component

<template>
  <v-text-field
    label="Geben Sie Zahlen ein"
    v-model="userInput"
    :rules="integerValueCheck"
    variant="outlined"
  ></v-text-field>
</template>

<script>
export default {
  data() {
    return {
      userInput: '',
      integerValueCheck: [
        v => !v || /^\d+$/.test(v) || 'Nur Zahlen erlaubt'
      ]
    }
  }
}
</script>

Optional: Handle Leading/Trailing Spaces

If you want to ignore accidental leading/trailing spaces (and treat a space-only input as "empty"), tweak the rule to trim the value first:

integerValueCheck: [
  v => !v.trim() || /^\d+$/.test(v.trim()) || 'Nur Zahlen erlaubt'
]

This way, a field with only spaces passes validation (same as empty), while non-space non-numeric characters still trigger the error.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.06 19:39:08