Steven Matthews
Steven Matthews

Reputation: 11275

Form Validation - How to use If and Else If

I am trying to do a Javascript form validation, and I want to set the formValue to 0 in several cases. That is, if ANY of the required fields are not filled out, the value should go to 0.

function formValidation() {
            var formValue = 1;

            if (document.getElementById('orgname').value == '') formValue = 0;
            else if (document.getElementById('culture[]').value == '') formValue = 0;
            else if (document.getElementById('category[]').value == '') formValue = 0;
            else if (document.getElementById('service[]').value == '') formValue = 0;

            if (formOkay == 1) {
           return true;
      } else if (formOkay == 0) {
           alert('Please fill out all required fields');
           return false;
      }
 }

Is there a more elegant way to do this?

EDIT: Script does not appear to be working, now.

Upvotes: 0

Views: 5608

Answers (4)

amiuhle
amiuhle

Reputation: 2773

Building upon @Baszz's second answer using jQuery, you could also build a more generic solution using HTML5 data- attributes:

$(function() {
  $('form').submit(function() {
    var toValidate = $(this).find('input[data-validation]');
    for(var i=0; i<toValidate.length; i++) {
      var field = $(toValidate[i]);
      if(field.val().search(new RegExp(field.data('validation'))) < 0) {
        alert("Please fill out all required fields!");
        return false;
      }
    }
  });
});

You can then specify regular expressions in your markup:

<form>
  <input type="text" data-validation=".+" />
</form>

For required fields you can use ".+" as a regular expression, meaning the user has to enter at least one character, but you can of course use the full potential of regular expressions to check for valid email addresses, phone numbers or zip codes etc...

Upvotes: 0

Merlyn Morgan-Graham
Merlyn Morgan-Graham

Reputation: 59101

I've done this in other languages using boolean logic, taking advantage of the & operator. It always returns false if any of the values are false.

Something like:

function formValidation() {
  var formValue = true;

  formValue &= document.getElementById('orgname').value != '';
  formValue &= document.getElementById('culture[]').value != '';
  formValue &= document.getElementById('category[]').value != '';
  formValue &= document.getElementById('service[]').value != '';

  if(!formValue) {
    alert('Please fill out all required fields');
  }

  return formValue;
}

This has the advantage of working for other scenarios where your logic is more complicated. Anything that evaluates in the end to true/false will fit right in with this solution.

Then I'd work on reducing logic duplication:

function formValidation() {
  var formValue = true;

  var elementIdsToCheck = ['orgname', 'culture[]', 'category[]', 'category[]'];
  for(var elementId in elementIdsToCheck) {
    formValue &= document.getElementById(elementId).value != '';
  }

  if(!formValue) {
    alert('Please fill out all required fields');
  }

  return formValue;
}

Upvotes: 1

jabclab
jabclab

Reputation: 15042

Something like this should help (this assumes that value attribute is available on the referenced elements):

var ids = ["orgname", "culture[]", "category[]", "service[]"],
    formValue = 1; // default to validation passing

for (var i = 0, len = ids.length; i < len; i++) {
    if (document.getElementById(ids[i]).value === "") {
       formValue = 0;
       break; // At least one value is not specified so we don't need to continue loop
    }
}

Upvotes: 0

Bas Slagter
Bas Slagter

Reputation: 9929

You can do some looping:

var toCheck = ['orgname', 'culture[]', 'category[]', 'category[]']
for(var id in toCheck )
{
    if(document.getElementById(id).value == ''){
        formValue = 0;
        break;
    }
}

A more elegant way can be that you specify a 'required' class on each input that you want to check and than do the following using jQuery:

$(document).ready(function(){
    var toCheck = $('.required');
    var formValue = 1;
    $.each(toCheck, function(index, element){
        if(element.val() == '')
           formValue = 0;
    });
});

Upvotes: 1

Related Questions