Search code examples
javascripthtmlformsrequired

Javascript Validation for all field with Required attribute


I've searched high and low for the answer to this but can't find it anywhere.

I have a form which has the HTML 'required' attributes and it does a fine job of highlighting the fields that need to filled in before submission...or would do, but the system which my form is bolted onto (of which I have no control over) submits the form anyway after a few seconds. It relies on Javascript for it's submission. Therefore I'd like to write a Javascript script to check all fields for a required attribute. Currently I have a script that specifies the fields I want to be mandatory, but if it could look up the attribute instead, that would be brilliant.


Solution

  • In case that input[type=submit] is used, you don't need any JavaScript

    <form id="theForm" method="post" acion="">
      <input type="firstname" value="" required />
      <input type="lastname" value="" required />
      <input type="submit" name="submit" value="Submit" />  
    </form>
    

    Working jsBin

    But if input[type=button] is used for submitting the form, use the snippet below

    <form id="theForm" method="post" acion="">
      <input type="firstname" value="" required />
      <input type="lastname" value="" required />
      <input type="button" name="button" value="Submit" />  
    </form>
    
    window.onload = function () {
      var form = document.getElementById('theForm');
      form.button.onclick = function (){
        for(var i=0; i < form.elements.length; i++){
          if(form.elements[i].value === '' && form.elements[i].hasAttribute('required')){
            alert('There are some required fields!');
            return false;
          }
        }
        form.submit();
      }; 
    };
    

    Wotking jsBin