純CSS實現表單驗證


ladies and 鄉親們,表單驗證你在做嗎?客戶端or服務器端,javascript or jquery,動手寫 or 使用插件,今天我們來探索下使用純css實現表單驗證,借以學習css selectors level 4中的表單相關的偽類選擇器。

案例欣賞

這里寫圖片描述
代碼我同樣放到了codepen,大家可以在線研究,或下載收藏

知識解析

關鍵在於使用css selectors levle4里的一些偽類實現表單驗證,這些偽類有:

  • :required和:optional
  • :in-range和out-of-range
  • :valid和:invalid
  • :read-only和:read-write

上面的案例就是使用了:in-range和:out-of-range,接下去我們來一一解讀下。

:required和:optional

:required可以選中具有required屬性的表單元素,可以是input、select和textarea,例如下面這些元素都會被選中。

<input type="name" required>
<input type="checkbox" required>
<input type="email" required>
<!-- and other input types as well.. -->
<textarea name="name" id="message" cols="30" rows="10" required></textarea>
<select name="nm" id="sel" required>
    <!-- options -->
</select>

:optional則選中不具有required屬性的表單元素,利用這兩個偽類我們可以實現下面這個有意思的效果。代碼同樣放在了codepen,在線研究or下載收藏,悉聽尊便。
這里寫圖片描述
本代碼主要利用:required和:optional兩個偽類對必選和選填的兩種表單實施不同的樣式,不同的提示文字。核心代碼如下所示。

/*可選表單樣式*/
input:optional,
select:optional {
  border-right: 3px solid #888;
  background-color: #f8f8f8;
  color: #888;
}
/*必選表單樣式*/
input:required,
textarea:required {
  border-right: 3px solid #aa0088;
}
/*可選表單提示文字*/
input:optional+label::after{
  content:"(可選)";
}
/*必選表單提示文字*/
input:required+label::after{
  content:"(必填)";
}
/*可選表單激活效果*/
input:optional:focus,
select:optional:focus {
  box-shadow: 0 0 2px 1px #aaa;
}
/*必選表單激活效果*/
input:required:focus,
select:required:focus,
textarea:required:focus {
  outline: 0;
  box-shadow: 0 0 2px 1px #aa0088;
}

:in-range和out-of-range

這兩個偽類分別選中表單屬性值在范圍內、范圍外兩個狀態,這兩個偽類可以用在接受數字范圍的元素上,例如type為number的表單或者sliders。案例效果如上面“案例欣賞”版塊所示,我們這里僅僅展示核心代碼,借以幫助大家理解兩個偽類的使用。

input:out-of-range{
  border: 1px solid tomato;
}
input:in-range~ label::after {
  content: "輸入一個正確的從1到10的數字";
}
input:out-of-range ~ label::after {
  content: "棗糕,你傻了!";
}

:valid和:invalid

這兩個偽類針對具有type的input表單而立,比如有一個type=email的表單,當它的值不是有效的郵箱格式時觸發:invalid偽類,值為有效的郵箱格式時觸發:valid偽類。
這里寫圖片描述
同樣,放在了codepen,請在線研究下載收藏,然后我們來看看核心代碼,如下所示。

input:invalid{
  border: 1px solid tomato;
}
input:valid~ label::after {
  content: "耶,一個郵箱!";
}
input:invalid ~ label::after {
  content: "棗糕,郵箱郵箱,是郵箱嗎?";
}

:read-only和:read-write

下面這些元素可以激活:read-only偽類。

  • 具有disabled屬性的表單
  • 具有read-only或disbaled屬性的text-area
  • 其他沒有指定contenteditable屬性的任何元素

例如下面代碼代碼所示的元素,都可以激活:read-only偽類選擇器。

<input type="text" disabled>
<input type="number" disabled>
<input type="number" readonly>
<textarea name="nm" id="id" cols="30" rows="10" readonly> </textarea>
<div class="random"> </div> <!-- regular element that is not editable with contenteditable -->

:read-write元素恰恰與:read-only元素相反。
這個比較簡單,就不再做案例。謝謝。

瀏覽器兼容情況

上述的幾個偽類選擇器在標准瀏覽器(chrome、safari、opera、firefox)里支持良好,IE支持不好。

深入閱讀

致謝

前端開發whqet,關注前端開發,分享相關資源。csdn專家博客,王海慶希望能對您有所幫助。
本文原文鏈接,http://blog.csdn.net/whqet/article/details/43449045
歡迎大家訪問獨立博客http://whqet.github.io


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM