1

I have a some custom validation for a small input form, that checks if a field is required. If it is a required field it alerts the user, if there is no value. At the moment it will validate all inputs other than check boxes.

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
    <div class="ss-item-required">
      <label>Question: What is your name?</label>
      <input type="text" name="name" id="name"></input>
    </div>
    <div class="ss-item-required">
      <label>Question: What is your email?</label>
      <input type="text" name="email" id="email"></input>
    </div>
    <div class="ss-item-required">
      <label>Question: What is your address?</label>
      <textarea name="address" rows="8" cols="75" id="address"></textarea>
    </div>
     <div class="ss-item-required">
      <label>Do you agree to out terms?</label>
      <input type="checkbox" name="Check_0">
    </div>

    <a href="#" onclick="formcheck(); return false">Submit</a>
 </form>
 
 <script>
 function formcheck() {
  var fields = $(".ss-item-required")
        .find("select, textarea, input").serializeArray();
  
  $.each(fields, function(i, field) {
    if (!field.value)
      alert(field.name + ' is required');
   }); 
  console.log(fields);
}
 </script>

If anyone can work out how to include validation of check boxes, it would be much appreciated.

4
  • See my updated answer for the solution. Commented Mar 22, 2019 at 16:34
  • 1
    Use a submit button and required attribute and you have your form's validation. Any customized validation should be set inside form submit handler. Commented Mar 22, 2019 at 16:39
  • I couldn't do that because of a requirement for the style of validation messages, but yes if anyone else come across this question A. Wolff is correct. Commented Mar 22, 2019 at 16:51
  • 1
    You can style the validation messages if you use the Validation API. Commented Mar 22, 2019 at 17:04

2 Answers 2

1

Even though some answers already provide a solution, I've decided to give mine, that will validate every required input in your form, regardless of being a checkbox (maintaining your each loop).

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
    <div class="ss-item-required">
      <label>Question: What is your name?</label>
      <input type="text" name="name" id="name">
    </div>
    <div class="ss-item-required">
      <label>Question: What is your email?</label>
      <input type="text" name="email" id="email">
    </div>
    <div class="ss-item-required">
      <label>Question: What is your address?</label>
      <textarea name="address" rows="8" cols="75" id="address"></textarea>
    </div>
     <div class="ss-item-required">
      <label>Do you agree to out terms?</label>
      <input type="checkbox" name="Check_0">
    </div>

    <a href="#" onclick="formcheck(); return false">Submit</a>
 </form>
 
 <script>
 function formcheck() {
  var fields = $(".ss-item-required")
  $.each(fields, function(i, field) {
    
    field=$(field).find('input, select, textarea')[0]
    if (!field.value || (field.type=='checkbox' && !field.checked))
      alert(field.name + ' is required');
   }); 
}
 </script>

The problems were:

  • serializeArray() would try to get the value from your checkbox, and because it returned nothing, the checkbox input was never added to fields!
  • Checkboxes don't have a property value, instead they are checked
Sign up to request clarification or add additional context in comments.

3 Comments

Thank-you, you're awesome :)
Checkboxes most certainly do have a value property. Without it, checking the checkbox would have no meaning.
They do have a value property yes, but its not what validates if the input is checked or not! Edit my answer and do console.log(field.name,field.value,field.checked). You'll see the value for the checkbox is always "on" opposed to checked that will alternate with true and false.
1

There is more than one way to determine this:

Check the length of the JQuery wrapped set that queries for only checked checkboxes and see if it is 1:

if($("input[name='Check_0']:checked").length === 1)

Check the checked property of the DOM element itself (which is what I'm showing below) for false. To extract the DOM element from the JQuery wrapped set, you can pass an index to the wrapped set ([0] in this case), which extracts just that one item as a DOM element and then you can use the standard DOM API.

if(!$("input[type='checkbox']")[0].checked)

NOTE: It's important to understand that all client-side validation can be easily bypassed by anyone who really wants to. As such, you should always do a second round of validation on the server that will be receiving the data.

FYI: You have some invalid HTML: There is no closing tag for input elements and for label elements, you must either nest the element that the label is "for" inside of the label or you must add the for attribute to the label and give it a value of the id of the element that the label is "for". I've corrected both of these things below:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
    <div class="ss-item-required">
      <label for="userName">Question: What is your name?</label>
      <input type="text" name="userName" id="userName">
    </div>
    <div class="ss-item-required">
      <label for="email">Question: What is your email?</label>
      <input type="text" name="email" id="email">
    </div>
    <div class="ss-item-required">
      <label for="address">Question: What is your address?</label>
      <textarea name="address" rows="8" cols="75" id="address"></textarea>
    </div>
     <div class="ss-item-required">
      <label for="Check_0">Do you agree to out terms?
        <input type="checkbox" name="Check_0">
      </label>
    </div>

    <a href="#" onclick="formcheck(); return false">Submit</a>
 </form>
 
 <script>
 function formcheck() {
  var fields = $(".ss-item-required")
        .find("select, textarea, input").serializeArray();
  
  $.each(fields, function(i, field) {
    if (!field.value){
      alert(field.name + ' is required');
    }
  }); 
  
  // Check to see if the input is a checkbox and if it's checked
  if(!$("input[type='checkbox']")[0].checked){
      alert("You must agree to the terms to continue.");
  }
}
 </script>


Personally (and I'm far from alone on this), the use of JQuery is way overused in today's world. When it came out, the standard DOM API wasn't as mature as it is now and JQuery made DOM element selection and manipulation very simple. Back then, JQuery was a Godsend.

Today, the DOM API has matured and much of what we use to rely on JQuery to make easy, can be done just as easily without JQuery. This means you don't have to reference the JQuery library at all (faster page loading) and you're code follows standards.

If you're interested, here's your code without JQuery:

<form>
    <div class="ss-item-required">
      <label for="userName">Question: What is your name?</label>
      <input type="text" name="name" id="userName">
    </div>
    <div class="ss-item-required">
      <label for="email">Question: What is your email?</label>
      <input type="text" name="email" id="email">
    </div>
    <div class="ss-item-required">
      <label for="address">Question: What is your address?</label>
      <textarea name="address" rows="8" cols="75" id="address"></textarea>
    </div>
     <div class="ss-item-required">
      <label for="Check_0">Do you agree to out terms?
        <input type="checkbox" name="Check_0">
      </label>
    </div>

    <a href="#" onclick="formcheck(); return false">Submit</a>
 </form>
 
 <script>
 function formcheck() {
  // Get all the required elements into an Array
  var fields = [].slice.call(document.querySelectorAll(".ss-item-required > *"));
  
   // Loop over the array:
   fields.forEach(function(field) {
     // Check for text boxes or textareas that have no value
     if ((field.type === "text" || field.nodeName.toLowerCase() === "textarea")
          && !field.value){
       alert(field.name + ' is required');
       // Then check for checkboxes that aren't checked
     } else if(field.type === "checkbox" && !field.checked){
       alert("You must agree to the terms to continue.");
     }
   }); 
}
 </script>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.