HTMLObjectElement: setCustomValidity() method

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.

Phương thức setCustomValidity() của giao diện HTMLObjectElement đặt thông báo hợp lệ tùy chỉnh cho phần tử.

Cú pháp

js
setCustomValidity(errorMessage)

Tham số

errorMessage

Thông báo dùng cho các lỗi hợp lệ.

Giá trị trả về

Không có (undefined).

Ngoại lệ

Không có.

Ví dụ

Trong ví dụ này, ta truyền ID của một phần tử input và đặt các thông báo lỗi khác nhau tùy thuộc vào việc giá trị bị thiếu, quá thấp, hay quá cao. Lưu ý rằng thông báo sẽ không được hiển thị ngay lập tức. Cố gắng gửi form sẽ hiển thị thông báo, hoặc bạn có thể gọi phương thức reportValidity() trên phần tử.

js
function validate(inputID) {
  const input = document.getElementById(inputID);
  const validityState = input.validity;

  if (validityState.valueMissing) {
    input.setCustomValidity("You gotta fill this out, yo!");
  } else if (validityState.rangeUnderflow) {
    input.setCustomValidity("We need a higher number!");
  } else if (validityState.rangeOverflow) {
    input.setCustomValidity("Thats too high!");
  } else {
    input.setCustomValidity("");
  }

  input.reportValidity();
}

Điều quan trọng là phải đặt thông báo thành chuỗi rỗng nếu không có lỗi. Miễn là thông báo lỗi không rỗng, form sẽ không vượt qua xác thực và sẽ không được gửi.

Thông số kỹ thuật

Specification
HTML
# dom-cva-setcustomvalidity-dev

Tương thích trình duyệt

Xem thêm