[英]Restrict input to 5 characters if whole number or 8 characters with fraction
我有簡單的文本輸入:
<div style="float:right" class="xField">
<input id="userLength" name="userLength"/>
<label style="margin-left: 3px;">m</label>
</div>
我需要這個輸入只接受數字,如果數字是整數,它應該只允許 5 個字符,即12345
。 如果該數字包含分數,則它應該允許 8 個字符,即12345,99
。
我試過將maxlength
添加到輸入中,但一次只適用於這些條件之一。
我怎樣才能做到這一點?
您可以使用pattern
屬性並提供支持您的要求的正則表達式。
例如(這並不禁止輸入無效數據,但會在模式不匹配時將字段標記為無效)。
<div style="float:right" class="xField"> <input id="userLength" name="userLength" pattern="\d{1,5}(,\d{1,2})?" /> <label style="margin-left: 3px;">m</label> </div>
你只需要這樣:
<form action="/" id="form">
<input pattern="\d{0,5}([,.]\d{1,2})?" title="max 5 digits and 2 decimals">
<button type="submit">submit</button>
</form>
這將允許用戶輸入任意數量的字符,但在表單驗證時,如果不滿足模式,表單將失敗。
該模式是一個正則表達式,內容如下:從 0 到 5 個數字字符,最多可選擇兩位小數
另外,如果輸入不應該為空,您可以像這樣添加一個必需的屬性
<input ... pattern="" required>
如果輸入為空,這也會導致驗證失敗。
當不符合模式時,瀏覽器將向用戶顯示title=""
中的內容。
玩弄這個小提琴,這樣您就可以看到驗證錯誤是如何呈現的: https ://jsfiddle.net/aqohfsrj/2/
此外,如果您想使用 javascript 對輸入值執行某些操作,我建議綁定到表單的提交事件,而不是按鈕的點擊或輸入的 enter-keydown 事件
document.getElementById("form").addEventListener("submit", e => {
// if this code is executed it means the validation passed, otherwise errors
// are displayed to the user and this code is not run.
e.preventDefault(); // <-- to avoid trying to use the form's action i.e. the browser will not navigate.
});
要了解我使用的正則表達式,您可以查看此 regex101 文件: https ://regex101.com/r/aHLI6u/1
最后一個建議:盡量避免使用maxlength
進行驗證; 很多時候我不得不在線填寫一張表格,例如要求提供信用卡,並且它被限制為maxlength="16"
這是個好主意,但是如果你試圖從復制你的信用卡怎么辦你有一張便條或其他東西,它被存儲為5430-0000-1111-2222
(帶破折號)。 當用戶想要的只是粘貼、然后編輯、然后提交時,禁止粘貼比允許的更多的字符感覺很粗魯。 我會讓用戶根據需要添加盡可能多的內容,這樣他們就可以就地編輯以刪除括號(對於手機)、刪除貨幣符號(對於金錢)、刪除破折號(對於信用卡)並在提交后進行驗證形式。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.