nbren007
nbren007

Reputation: 313

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.

Upvotes: 23

Views: 90412

Answers (6)

Frank
Frank

Reputation: 89

If using either the simple "required" solution above or the "Constraint Validation API" solution, how do you make a select option required if it is contingent on another select field having a certain answer. I used the "required" method as you can see below which works great for Country select.

<select  id="country_code" name="country_code" required>
<option value="">--None--</option>
<option value="AL">Albania</option>
<option value="US">United States</option>
</select>

<script>
    $("select[name='country_code']").change(function() {
      if ($(this).val() == "US") {
        $("select[name='state_code'] option").removeClass('hidden');
        $("select[name='state_code'] option").addClass('required');
      } else {
      } else {
        $("select[name='state_code'] option").addClass('hidden');
      }
    });
</script> 

<label for="state_code">State/Province</label>
<select  id="state_code" name="state_code">
<option value="">--None--</option>
<option value="AL">Alabama</option>
<option value="AK">Alaska</option>
</select>

As you can see, I tried adding the class "required" to State select if Country select is US, but it didn't do anything.

Upvotes: 0

Ken
Ken

Reputation: 663

I'm late to the party but this worked for me.

<input type="firstname" value="" required />
document.getElementById('theForm').reportValidity();
if (check) {
    //success code here
    return true;
}

Credit to Vlad and a.l.e for pointing me in the right direction with their previous answers. This is a simplified version of their approach.

Upvotes: 8

a.l.e
a.l.e

Reputation: 868

Many years later, here is a solution that uses some more modern Javascript:

for (const el of document.getElementById('form').querySelectorAll("[required]")) {
  if (!el.reportValidity()) {
    return;
  }
}

See Vlad's comment for a link to the Constraint Validation API (thanks Vlad, that helped!)

Upvotes: 11

Vlad
Vlad

Reputation: 844

You can use Constraint validation API, which is supported by most browsers.

Upvotes: 3

Jason Liu
Jason Liu

Reputation: 9

this will be validating all your form field types

$('#submitbutton').click(function (e) {
    e.preventDefault();

    var form = document.getElementById("myForm");
    var inputs = form.getElementsByTagName("input"), input = null, select = null, not_pass = false;
    var selects = form.getElementsByTagName("select");
    for(var i = 0, len = inputs.length; i < len; i++) {
        input = inputs[i];

        if(input.type == "hidden") {

            continue;
        }

        if(input.type == "radio" && !input.checked) {
            not_pass = true;
        } 
        if(input.type == "radio" && input.checked){
            not_pass = false;
            break;
        }

        if(input.type == "text" && !input.value) {
            not_pass = true;
        } 
        if(input.type == "text" && input.value){
            not_pass = false;
            break;
        }

        if(input.type == "number" && !input.value) {
            not_pass = true;
        } 
        if(input.type == "number" && input.value){
            not_pass = false;
            break;
        }

        if(input.type == "email" && !input.value) {
            not_pass = true;
        } 
        if(input.type == "email" && input.value){
            not_pass = false;
            break;
        }

        if(input.type == "checkbox" && !input.checked) {
            not_pass = true;
        } 
        if(input.type == "checkbox" && input.checked) {
            not_pass = false;
            break;
        }
    }

    for(var i = 0, len = selects.length; i < len; i++) {
        select = selects[i];
        if(!select.value) {
            not_pass = true;
            break;
        } 
    }

    if (not_pass) {
        $("#req-message").show();//this div # in your form
        return false;
    } else {
     //do something here 
    }
});

Upvotes: 0

hex494D49
hex494D49

Reputation: 9235

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

Upvotes: 27

Related Questions