Vuetify v-text-field数字校验问题:空值不应触发错误
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, orundefined). 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

