3
\$\begingroup\$

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 == "") {
 $('#ziplabel').css('color','#fff');
 pass = false;
 } else {
 $('#ziplabel').css('color','#444');
 }
 x = $('input#fname').val();
 if (x == null || x == "") {
 $('#fnamelabel').css('color','#fff');
 pass = false;
 } else {
 $('#fnamelabel').css('color','#444');
 }
 x = $('input#lname').val();
 if (x == null || x == "") {
 $('#lnamelabel').css('color','#fff');
 pass = false;
 } else {
 $('#lnamelabel').css('color','#444');
 }
}
Jamal
35.2k13 gold badges134 silver badges238 bronze badges
asked Feb 6, 2014 at 21:22
\$\endgroup\$

1 Answer 1

5
\$\begingroup\$

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.

answered Feb 6, 2014 at 21:29
\$\endgroup\$
1
  • 1
    \$\begingroup\$ You could avoid the caching line if you use $(this).prev('label').toggleClass('invalid',this.value) \$\endgroup\$ Commented Feb 7, 2014 at 4:46

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.