前端對表單輸入信息的格式進行驗證有很多方法,下面兩種方式效果比較不錯也很簡單。其中第一種僅在點擊提交按鈕后顯示,而第二種很靈活。
對於使用Bootstrap開發的前端,感覺第二種風格比較統一。
第一種:利用html5的新特性
在<input>標簽中加入新的屬性
required:要求不能為空
patten=”正則表達式”:設置內容的格式
title=”提示信息”:彈出框的顯示內容
這一種比較簡單,沒有利用Bootstrap的特性。效果如下:
第二種:配合bootstrap的樣式表
有一些現成的驗證插件,但自己寫也比較簡單。利用bootstrap中表單不同狀態不同樣式,以及對應的圖標和幫助文字,主要工作就是判斷信息格式,根據結果修改對應標簽的class。
這里修改了<div>:form-group has-feedback has-success(has-error)
幫助文字以及圖標的class。
一個簡單例子如下:
html代碼:
<div id="accountDiv"class="form-group has-feedback"> <label>用戶名</label>
<input type="text" name="account" id="account" class="form-control" placeholder="請輸入6-16位字符" onclick="check_info()" required pattern="[a-z0-9A-Z]{6,16}" title="帳號應為6-16位的字母或數字"> <span id="accountIcon" class="hide"></span> <br><br><br> <span id="account_warning" class="help-block hide">賬號為6-16位字符</span> </div>
js代碼:
var account = document.getElementById("account").value; if ((account.length != 0) && ((account.length < 6) || (account.length >16))) { document.getElementById("account_warning").className = "help-block"; document.getElementById("accountDiv").className="form-group has-error has-feedback"; document.getElementById("accountIcon").className="glyphicon glyphicon-remove form-control-feedback"; } else if(account.length != 0) { document.getElementById("account_warning").className = "help-block hide"; document.getElementById("accountDiv").className="form-group has-success has-feedback"; document.getElementById("accountIcon").className="glyphicon glyphicon-ok form-control-feedback"; all_info_are_right--; } else { document.getElementById("account_warning").className = "help-block hide"; document.getElementById("accountDiv").className="form-group has-feedback"; document.getElementById("accountIcon").className="hide"; }
效果如下: