views:

773

answers:

5

Hello, I'm trying to figure out what would be the simplest way to validate required fields without having to do an if statement for each element's name. Perhaps just with a loop and verify its class.

What I'm trying to accomplish is to check only the ones that have the class name as "required"

<input name="a1" class="required" type="text" />
<input name="a2" class="" type="text" />
<input name="a3" class="required" type="text" />

Thanks

A: 

I would recommend you to use this javascript based css selector wich will get all elements of a specific class. Validating the form just like the way you mentioned.

Ricardo Acras
+2  A: 

I use the jQuery validation plugin. Works really well and fits your stated desire to only need class attributes.

 $(document).ready( function() {
     $('form').validate();
 });

Is all it takes to set up the validation once you have your required fields marked.

tvanfosson
+5  A: 

I'm not at all against the libraries suggested by others, but I thought that you may want some samples of how you could do it on your own, I hope it helps.

This should work:

function validate() {
    var inputs = document.getElementsByTagName("input");

    for (inputName in inputs) {
        if (inputs[inputName].className == 'required' && inputs[inputName].value.length == 0) {
            inputs[inputName].focus();
            return false;
        }
    }

    return true;       
}

Also lets say your inputs are in a form named "theForm":

function validate() {
    for (var i = 0; i < theForm.elements.length; i++) {
        if (theForm.elements[i].className == "required" && theForm.elements[i].value.length == 0) {
            theForm.elements[i].focus();
            return false;
        }
    }

    return true;
}

Of course you would trim the value and/or add the appropriate validation logic for the application, but I'm sure you can get the idea from the sample.

You can also store arbitrary data on the input itself and read it using the getAttribute() method on the element. For example you could have this element in your html (regex requires a 3 digit number):

<input name="a1" validate="true" regex="[0-9]{3}" type="text" />

you could use this method to run the regex in the validation routine.

function validate() {
    for (var i = 0; i < theForm.elements.length; i++) {
        var elem = theForm.elements[i];

        if (elem.getAttribute("validate") == "true") {
            if (!elem.value.match(elem.getAttribute("regex"))) {
                elem.select();
                return false;
            }
        }
    }

    return true;
}

Hope this helps.

Ryan Cook
A: 

A pattern for this that I have been using for a long time and has served me well is wrapping the control with a DIV, or P and marking that as required.

<div class="form-text required">
  <label for="fieldId">Your name</label>
  <input type="text" name="fieldName" id="fieldId" value="" />
</div>

This means that I can pick out the required fields to validate easily with a CSS selector.

.required input, .required select

In jQuery, you can test input with something like this:

$('form').submit(function(){
  var fields = $(this).find('input, textarea, select'); // get all controls
  fields.removeClass('invalid'); // remove
  var inv = $(this).find('input[value=""], select[value=""]');  // select controls that have no value
  if (inv.length > 0) {
    inv.addClass('invalid'); // tag wrapper 
    return false; // stop form from submitting
  }
  // else we may submit
});

In plain Javascript it would be more than I care to type out, but along the lines of:

var badfields = [];
var fields = theForm.getElementsByTagName('input');
for (var i=0; i< fields.length; i++ ) {
   if ( fields[i] && fields[i].parentNode && fields.value == '' &&
       /(^| )required( |$)/.test( fields[i].parentNode.className ) ) {
     badfields.push( fields[i] );
   }
}
// badfields.length > 0 == form is invalid

The most immediate benefit of wrapping the label and input (and optionally: hint text, error...) as a control "set" in this way is that you can apply CSS styles on the input and label together.

.required input, .required select {
  border : 1px solid red;
}
.required label {
  color : #800;
}
.invalid input, .invalid select {
  background-color : #f88;
}

I recommend using a ready made solution for your form validation as things can quickly add on: How will you validate checkboxes? Can checkboxes be required? (EULA?) What about radio buttons, how will you check those?

Most validation solutions will also provide sugar such as verifying correct data (say, email addresses) rather than just checking if it's there.

Borgar
A: 

I'm a little surprised that no one mentioned YUI. You can easily use getElementsByClassName method of Dom class in the following manner:

var aElements = YAHOO.util.Dom.getElementsByClassName('required', 'input');
for (var i = 0; i < aElements.length; i++)
{
   // Validate
}

More method information is available here and more general info is here

MK_Dev