Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Ngăn chặn xác thực trên textbox HTML5 (formnovalidate)

Để submit form không kích hoạt xác thực HTML5 (required, pattern, min/max...), dùng thuộc tính formnovalidate trên nút submit.

Ví dụ

<!DOCTYPE html>
<html>
  <head>
    <title>HTML formnovalidate attribute</title>
  </head>
  <body>
    <form action="new.php" method="get">
      Rank <input type="number" name="rank" required><br>
      <input type="submit" value="Gửi (có xác thực)"><br>
      <input type="submit" formnovalidate="formnovalidate" value="Gửi (KHÔNG xác thực)">
    </form>
  </body>
</html>

Giải thích

  • Nút đầu: Submit bình thường → trình duyệt kiểm tra required trên rank, chặn nếu trống.
  • Nút thứ hai: Có formnovalidate → bỏ qua tất cả validation, submit ngay.

Các trường hợp dùng

  • Nút "Lưu nháp" (Save draft) - không bắt buộc điền đủ.
  • Nút "Hủy bỏ" / "Quay lại" - thoát form mà không validate.
  • Nút "Tìm kiếm" trong form có field required khác.

Lưu ý

  • formnovalidate chỉ áp dụng cho <input type="submit"> và <button type="submit">.
  • Có thể dùng trên <form> attribute novalidate để tắt validation cho toàn form.
  • Validation phía server luôn bắt buộc bất kể client có validate hay không.