Live validation of Radio/checkbox buttons in JavaScript

Viewed 43

This is a excerpt of my js file for creating new books in the database and my validation approach for textfields which worked:

//...
function pressHandlerTitle() {
  var bookfield = document.getElementById("Book");
  if (!bookfield.elements[1].value) {
    bookfield.elements[1].setCustomValidity("title must be provided");
  } else {
    var title = bookfield.elements[1].value;
    bookfield.elements[1].setCustomValidity("")
  }

  if (!(typeof (title) === "string" && title.trim() !== "")) {
    bookfield.elements[1].setCustomValidity("The title must be a non-empty string!");
  } else {
    bookfield.elements[1].setCustomValidity("");
  }
  bookfield.elements[1].reportValidity();
}
//...
function setupUserInterface() {
  const formEl = document.forms["Book"],
  otherAvailLangSelEl = formEl["otherAvailableLanguages"],
  categoryFieldsetEl = formEl.querySelector("fieldset[data-bind='category']"),
  pubFormsFieldsetEl = formEl.querySelector("fieldset[data-bind='publicationForms']"),
    saveButton = formEl.commit;

  document.getElementById("isbn").addEventListener("keyup", pressHandlerIsbn);
  document.getElementById("title").addEventListener("keyup", pressHandlerTitle);
//here there should be the other eventlisteners for the radio button fieldsets
//...

and my HTML looks like this (Flask syntax with Python):

<!-- ... -->
<form id="Book">
<div><label>ISBN: <input type="text" name="isbn" id="isbn"/></label></div>
<div><label>Title: <input type="text" name="title" id="title"/></label></div>
<!-- ... -->
<fieldset data-bind="category">
    <legend>Category</legend>
      {% for item in ["novel", "biography", "textbook", "other"] %}
       <input type="radio" name="unique" value="{{ item }}">{{ item }}<br>
      {% endfor %}
</fieldset>
<fieldset data-bind="publicationForms">
    <legend>Publication forms</legend>
      {% for item in ["PDF", "ePub", "Paperback", "Hardcover"] %}
       <input type="checkbox" name="{{ item }}" value="{{ item }}">{{ item }}<br>
      {% endfor %}
  </fieldset>

Now, I tried to implement live validation in a similar way as for the Title/Isbn textboxes in order to notify the user if no category (e.g. novel && biography && textbook && other is not selected) or no publication form is selected (PDF && ePub && Paperback && Hardcover not selected), but this doesn't work unfortunately. Can you help me on how to add live validation to radio buttons? I've tried to use different events, e.g. the mouseover event to notify the user of no selected button every time he hovers over the elements of the fieldset. I've tried the getElementsByName function etc. and also tried all methods I found on this site with no success.

0 Answers
Related