我试图向输入元素表单显示一条错误消息,以向用户显示特定时间不可用。我已经查看了约束验证API的不同示例,但我不确定如何为时间表实现此功能。有人可以举个例子请解释一下。
var time = document.getElementById("#validtime");
time.addEventListener("input", function(event) {
if (time.validity) {
time.setCustomValidity("time is not avalible, please choose a different time");
} else {
time.setCustomValidity("");
}
});
<div class="form-group">
<label for="time">Time</label>
<input type="time" name="time" class="form-control" required>
</div>
你的代码中有一些错误。无论如何,我们假设您不希望用户输入时间“00:00”。在这种情况下,您可以执行以下操作:
document.querySelector('[type=submit]').style.visibility='hidden';
document.getElementById("validtime").addEventListener("input", function (event) {
if ("00:00|01:00|11:00".indexOf(this.value) != -1) {
this.setCustomValidity("time is not avalible, please choose a different time");
this.closest('form').querySelector('[type=submit]').click();
} else {
this.setCustomValidity("");
}
});
<form>
<div class="form-group">
<label for="validtime">Time</label>
<input id="validtime" type="time" name="time" class="form-control" required>
</div>
<input type="submit" value="Validate">
</form>