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

Thuộc tính novalidate trong HTML

Thuộc tính novalidate trong HTML chỉ định rằng dữ liệu biểu mẫu không được kiểm tra tính hợp lệ khi submit. Đây là một thuộc tính boolean.

Cú pháp

<form novalidate></form>

Ví dụ

Ví dụ minh họa sự khác biệt khi có và không có thuộc tính novalidate:

<!DOCTYPE html>
<html>
<style>
  body {
    color: #000;
    height: 100vh;
    background: linear-gradient(62deg, #FBAB7E 0%, #F7CE68 100%) no-repeat;
    text-align: center;
  }
  input[type='text'] {
    width: 300px;
    padding: 8px 16px;
    border: 2px solid #fff;
    background: transparent;
    border-radius: 20px;
    display: block;
    margin: 1rem auto;
    outline: none;
  }
  .btn {
    background: #db133a;
    border: none;
    height: 2rem;
    border-radius: 20px;
    width: 330px;
    display: block;
    color: #fff;
    outline: none;
    cursor: pointer;
    margin: 1rem auto;
  }
  ::placeholder { color: #000; }
</style>
<body>
<h1>Demo thuộc tính novalidate</h1>
<form>
  <input type="text" placeholder="Nhập tên của bạn" required>
  <input type="submit" value="Gửi" class="btn" onclick='check()'>
</form>
<button type='button' class="btn" onclick="setNoValidate()">Bật novalidate</button>
<div class="show"></div>
<script>
  function setNoValidate() {
    document.querySelector('form').setAttribute('novalidate', 'true');
    document.querySelector('.show').innerHTML = '<p style="color:green">Đã bật novalidate - biểu mẫu sẽ không bị kiểm tra</p>';
  }
</script>
</body>
</html>

Kết quả

  1. Thử nhấn "Gửi" không nhập tên → trình duyệt hiển thị cảnh báo validation.
  2. Nhấn "Bật novalidate" sau đó submit lại → biểu mẫu được gửi mà không có cảnh báo.

Lưu ý: Thuộc tính này hữu ích khi bạn muốn tự xử lý validation bằng JavaScript.