Code Review Stack Exchange is a question and answer site for peer programmer code reviews. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I've got some pretty simple validation that I'm working on, but it seems like I'm repeating myself a bunch of times. There has to be a better way of doing this. I'm simply checking if there is a value filled in for specific fields and apply a color if the value isn't filled in. There are also other areas where the validation is different where I'm checking a valid phone number. So I couldn't simply apply this to all inputs. Here's some of my code:

var x = $();
var pass = true;

function validateForm(){
        x = $('input#zip').val();
        if (x == null || x == "") {
            pass = false;
        } else {
        x = $('input#fname').val();
        if (x == null || x == "") {
            pass = false;
        } else {
        x = $('input#lname').val();
        if (x == null || x == "") {
            pass = false;
        } else {

share|improve this question
up vote 5 down vote accepted

Yup, you can iterate the input fields. For this sort of thing you should also be using classes, instead of inline CSS. Using jQuery .each and .togggleClass you can create something like this:

function validate () {

  $('#form input').each(function () {
     var $el = $(this)
     $el.prev('label').toggleClass('invalid', $el.val()); 


And your stylesheet has a rule like this;

label {
  color: #444;

label.invalid {
  color: #fff;

If you want to check if the form was valid then you can check for the existence of a field with that class. $('#form input.invalid').length. Or you can set a boolean in the each function if you want to separate the logic from the HTML.

share|improve this answer
You could avoid the caching line if you use $(this).prev('label').toggleClass('invalid',this.value) – elclanrs Feb 7 '14 at 4:46

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.