charly
charly

Reputation: 193

how can setCustomValidity() API be used to add an error message to time form

I am trying to show an error message to input element form to show the user that a particular time is not available. i have looked at different examples of constraints validation API , but i am not sure how to implement this for time form. can someone show an example please to explain this.

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>

Upvotes: 1

Views: 242

Answers (1)

gaetanoM
gaetanoM

Reputation: 42054

You have some mistakes in your code. In any case, let's assume you do not want the user can enter the time "00:00". In this case you may do something like:

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>

Upvotes: 2

Related Questions