
HTMX - 驗證
HTMX 驗證與 HTML5 驗證 API 協同工作,因為如果可驗證的輸入欄位無效,它不會觸發表單的任何請求。這在 Ajax 請求和 WebSockets 傳送中都以相同的方式工作。它將在驗證周圍觸發事件,這些事件可用於掛鉤自定義驗證和錯誤處理。
- htmx:validation:validate: 用於新增自定義驗證邏輯。
- htmx:validation:failed: 用於指示無效輸入。
- htmx:validation:halted: 用於顯示驗證錯誤。
HTMX 驗證示例
在以下示例中,hx-on 屬性捕獲 htmx:validation:validate 事件,並要求輸入值“tutorialspoint”。請記住,所有客戶端驗證都應在伺服器端重新執行,因為這始終可以繞過。
<form id="example-form" hx-post="/test"> <input name="example" // Reset the validation on keyup onkeyup="this.setCustomValidity('')" hx-on:htmx:validation:validate="if(this.value != 'tutorialspoint') { // Set the validation error this.setCustomValidity('Please enter the value tutorialspoint') // Report the issue htmx.find('#example-form').reportValidity() }" /> </form>
如何驗證非表單元素?
您可以在 hx-validate 屬性上設定 true 值,以在非表單元素髮出任何請求之前對其進行驗證。表單元素預設在發出任何請求之前進行驗證。
非表單元素驗證示例
在以下示例中,非表單元素在發出請求之前進行驗證。
- 輸入欄位具有 required 屬性,使其成為必填項。
- div 元素使用 hx-get 在單擊時向 /validate-username 傳送 GET 請求。
- hx-validate="true" 屬性確保在發出請求之前驗證輸入欄位。
- 伺服器的響應將顯示在 ID 為 result 的 div 中。
<input type="text" id="username" required placeholder="Enter your username" /> <div hx-get="/validate-username" hx-validate="true" hx-trigger="click" hx-target="#result" > Validate Username </div> <div id="result"></div>
廣告