示例代碼:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form action=""> <!--email提供了默認的電子郵箱的完整驗證:要求必須包含@符號,同時必須包含服務器名稱,如果不能滿足驗證,則會阻止當前的數據提交--> 郵箱:<input type="email"> <br> <!--tel它並不是來實現驗證。它的本質目的是為了能夠在移動端打開數字鍵盤。意味着數字鍵盤限制了用戶只能輸入數字。 如何查看效果:qq發送文件>>手機端使用qq來接收>>使用手機瀏覽器查看--> 電話:<input type="tel"> <br> <!--驗證只能輸入合法的網址:必須包含http://--> 網址:<input type="url"> <br> <!--number:只能輸入數字(包含小數點),不能輸入其它的字符 max:最大值 min:最小值 value:默認值--> 數量:<input type="number" value="60" max="100" min="0"> <br> <!--search:可以提供更人性化的輸入體驗--> 請輸入商品名稱:<input type="search"> <br> <!--range:范圍--> 范圍:<input type="range" max="100" min="0" value="50"> <br> 顏色:<input type="color"> <br> <!--日期時間相關--> <!--time:時間:時分秒--> 時間:<input type="time"> <br> <!--date:日期:年月日--> 日期:<input type="date"> <br> <!--datetime:大多數瀏覽器不能支持datetime.用於屏幕閱讀器--> 日期時間:<input type="datetime"><br> <!--datetime-local:日期和時間--> 日期時間:<input type="datetime-local"> <br> 月份:<input type="month"> <br> 星期:<input type="week"> <!--提交--> <input type="submit"> </form> </body> </html>
補充:郵箱驗證及其他驗證,當input標簽上有required屬性時瀏覽器才會在表單提交前自動執行驗證
當驗證不通過時觸發invalid事件,通過表單元素DOM對象方法setCustomValidity("提示信息")可以改變默認的提示信息
document.getElementById("userPhone").oninvalid=function(){ /*設置默認的提示信息*/ this.setCustomValidity("請輸入合法的11位手機號"); }