Не знаю, откуда этот код, но вот как я это сделаю:
<input type="checkbox" name="terms" value="accept" id="accept" required />
Обратите внимание на добавление обязательного атрибута.
document.querySelector('#accept').setCustomValidity('Please accept the terms and conditions');
Теперь, когда пользовательотправляет форму, она будет отображать ваше сообщение, если флажок не установлен, форма не будет отправлена.Вы можете проверить это, поместив оператор console.log
или debugger
в ваш обработчик отправки:
// Note that as I said in the comments, attaching the handler
// this way is preferable to using the onsubmit HTML attribute.
document.querySelector('#form1').addEventListener('submit', function(evt) {
console.log('stop the presses!');
});