正则表达式仅允许数字却放行字符:input pattern测试异常求助
Fixing Your Number Input Validation Issue
Let's break down why your current regex [1-9]\d*(\.\d+) is failing to block inputs like 'hello' and not meeting your integer/float requirements:
Key Problems with Your Current Regex
- Forces a decimal point: The
(\.\d+)part requires a decimal followed by digits, so valid integers like5will be rejected — that's not what you want. - Doesn't account for leading zero valid cases: It blocks valid inputs like
0or0.123since it starts with[1-9]. - HTML attribute escape issue: In HTML, backslashes are escape characters. Writing
\dor\.directly in thepatternattribute gets stripped, turning your regex into[1-9]d*(.d+)— which is basically useless, so the browser doesn't validate anything properly (hence why 'hello' slips through).
The Corrected Solution
First, use a regex that supports both integers and valid decimals, then properly escape the backslashes for HTML:
<input type="text" name="RoomPreference" pattern="^(0|[1-9]\\d*)(\\.\\d+)?$" required>
Let's Break Down This Regex
^and$: Explicitly anchor the regex to match the entire input (though HTML'spatternimplicitly does this, it's good to be explicit here for clarity).(0|[1-9]\\d*): Matches valid integers:0: Allows the single integer0[1-9]\\d*: Allows integers starting with 1-9 followed by any number of digits (no leading zeros for multi-digit integers)
(\\.\\d+)?: Makes the decimal part optional (the?means zero or one occurrence):\\.\\d+: Matches a decimal point followed by one or more digits
required: Ensures empty inputs aren't allowed (remove this if empty should be accepted, but that's unlikely for a room preference number)
Additional Notes
- If you want to allow negative numbers, adjust the regex to
^-?(0|[1-9]\\d*)(\\.\\d+)?$ - Test it thoroughly: Valid inputs like
0,123,0.456,78.9will pass, whilehello,12a3,012,.5(no leading zero) will be blocked.
内容的提问来源于stack exchange,提问作者pip
相关产品推荐
相关产品推荐

