0

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.

Steven Matthews
  • 9,705
  • 45
  • 126
  • 232

4 Answers4

1

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;
    });
});
Bas Slagter
  • 9,831
  • 7
  • 47
  • 78
1

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;
}
Merlyn Morgan-Graham
  • 58,163
  • 16
  • 128
  • 183
  • "the entity name must immediately follow the & in the entity reference" - what does this mean? - my IDE, netbeans, wrote this. – Steven Matthews Dec 05 '11 at 14:04
  • @AndrewAlexander: Hmm, maybe JS doesn't support the `&=` operator, but only supports the `&` operator. I'll edit my answer to fix this. – Merlyn Morgan-Graham Dec 05 '11 at 14:08
  • @AndrewAlexander: I think that error might be the way you're putting your code into your HTML file. You may need to escape your `&` as an entity reference: `&`. Rolling back my changes because the code is cleaner with `&=`, if it works... – Merlyn Morgan-Graham Dec 05 '11 at 14:13
  • &= does not seem to work. & seemed to work fine in place. – Steven Matthews Dec 05 '11 at 14:18
  • Actually, used &, and it says "& is not defined" – Steven Matthews Dec 05 '11 at 14:25
  • @AndrewAlexander: Maybe ignore the error the IDE is giving, and test it? If `formValue &=` doesn't end up working, try `formValue = formValue &` and let me know if that works instead. Also, check this: http://stackoverflow.com/questions/66837/when-is-a-cdata-section-necessary-within-a-script-tag – Merlyn Morgan-Graham Dec 05 '11 at 14:34
0

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
    }
}
jabclab
  • 14,786
  • 5
  • 54
  • 51
0

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...

amiuhle
  • 2,673
  • 1
  • 19
  • 28
  • You can add regular expressions to HTML mark-up?! This is phenomenal! I didn't know that! – Steven Matthews Dec 05 '11 at 14:16
  • @andrew-alexander You can add any string to HTML5 `data-` attributes, which of course can contain regular expressions. Corrected the code snippets after a quick test in Chrome 15.x – amiuhle Dec 05 '11 at 14:25