最近有點時間摳了一些細節, 之前項目的表單驗證比較奔放, 比如H5手機號輸入框,可以輸入文字, 移動端點擊彈出來的鍵盤不是數字鍵盤, 今天找了點時間優化一下
先上最終效果
這裏主要是做了兩點
1、 input 的 pattern 屬性配合樣式進行同步提示, 在此處表現就是輸入錯誤的時候輸入框爲紅色, 正確的時候爲綠色
2、還有就是直接限制不能輸入字符,這一點可能途中提現不出來
優化過程
1、讓移動端直接彈出數字鍵盤
將input 的 type='"tel" 我這裏設置的是 tel ,當然也可以設置成 number或者 pattern="[0-9]*" 這裏幾點都無法滿足全部要求
type="number" 的時候 pattern="^1[3456789]\d{9}$" 無法生效, 不能配合css 做提示
2、限制輸入字符
這個就直接使用 watch 監聽輸入做正則截取 newValue.replace(/[^\d]/g, '').substring(0, 11)
代碼
<input type="tel" v-model="form_01.input_04"
pattern="^1[3456789]\d{9}$" required placeholder="請輸入11位手機號">
watch: {
'form_01.input_04': function (newValue, oldValue) {
this.form_01.input_04 = newValue.replace(/[^\d]/g, '').substring(0, 11)
}
}
input,select{
...
&:focus:valid{
border-color: #77c25b; // 獲取光標 內容判斷合法提示的樣式
}
&:focus:invalid{
border-color: #ff1220; // 獲取光標 內容判斷不合法的樣式
}
}
這樣的表單驗證是比較友好的