0

I have rather large form and along with PHP validation (ofc) I would like to use jQuery. I am a novice with jQuery, but after looking around I have some code working well. It is checking the length of a Text Box and will not allow submission if it is under a certain length. If the entry is lower the colour of the text box changes Red.

The problem I have is as the form is so large it is going to take a long time, and a lot of code to validate each and every box. I therefore wondered is there a way I can loop through all my variables rather than creating a function each time.

Here is what I have:

var form = $("#frmReferral");
var companyname = $("#frm_companyName");
var companynameInfo = $("#companyNameInfo");
var hrmanagername = $("#frm_hrManager");
var hrmanagernameInfo = $("#hrManagerInfo");

form.submit(function(){
    if(validateCompanyName() & validateHrmanagerName())
        return true
    else
        return false;
});

Validation Functions

function validateCompanyName(){
    // NOT valid
    if(companyname.val().length < 4){
        companyname.removeClass("complete");
        companyname.addClass("error");
        companynameInfo.text("Too Short. Please Enter Full Company Name.");
        companynameInfo.removeClass("complete");
        companynameInfo.addClass("error");
        return false;
    }
    //valid
    else{
        companyname.removeClass("error");
        companyname.addClass("complete");
        companynameInfo.text("Valid");
        companynameInfo.removeClass("error");
        companynameInfo.addClass("complete");
        return true;
    }
}

function validateHrmanagerName(){
    // NOT Valid
    if(hrmanagername.val().length < 4){
        hrmanagername.removeClass("complete");
        hrmanagername.addClass("error");
        hrmanagernameInfo.text("Too Short. Please Enter Full Name.");
        hrmanagernameInfo.removeClass("complete");
        hrmanagernameInfo.addClass("error");
        return false;
    }
    //valid
    else{
        hrmanagername.removeClass("error");
        hrmanagername.addClass("complete");
        hrmanagernameInfo.text("Valid");
        hrmanagernameInfo.removeClass("error");
        hrmanagernameInfo.addClass("complete");
        return true;
    }
}

As you can see for 50+ input boxes this is going to be getting huge. I thought maybe a loop would work but not sure which way to go about it. Possibly Array containing all the variables? Any help would be great.

2
  • use a validation framework like jquery validator Commented Aug 17, 2013 at 16:24
  • Yup, agree with @ArunPJohny. Use a plugin. Its easy to use and getting help Commented Aug 17, 2013 at 16:29

3 Answers 3

1

This is what I would do and is a simplified version of how jQuery validator plugins work.

Instead of selecting individual inputs via id, you append an attribute data-validation in this case to indicate which fields to validate.

<form id='frmReferral'>
  <input type='text' name='company_name' data-validation='required' data-min-length='4'>
  <input type='text' name='company_info' data-validation='required' data-min-length='4'>
  <input type='text' name='hr_manager' data-validation='required' data-min-length='4'>
  <input type='text' name='hr_manager_info' data-validation='required' data-min-length='4'>
  <button type='submit'>Submit</button>
</form>

Then you write a little jQuery plugin to catch the submit event of the form, loop through all the elements selected by $form.find('[data-validation]') and execute a generic pass/fail validation function on them. Here's a quick version of what that plugin might look like:

$.fn.validate = function() {
  function pass($input) {
    $input.removeClass("error");
    $input.addClass("complete");
    $input.next('.error, .complete').remove();
    $input.after($('<p>', {
      class: 'complete',
      text: 'Valid'
    }));
  }

  function fail($input) {
    var formattedFieldName = $input.attr('name').split('_').join(' ');
    $input.removeClass("complete");
    $input.addClass("error");
    $input.next('.error, .complete').remove();
    $input.after($('<p>', {
      class: 'error',
      text: 'Too Short, Please Enter ' + formattedFieldName + '.'
    }));
  }

  function validateRequired($input) {
    var minLength = $input.data('min-length') || 1;
    return $input.val().length >= minLength;
  }

  return $(this).each(function(i, form) {
    var $form = $(form);
    var inputs = $form.find('[data-validation]');
    $form.submit(function(e) {
      inputs.each(function(i, input) {
        var $input = $(input);
        var validation = $input.data('validation');
        if (validation == 'required') {
          if (validateRequired($input)) {
            pass($input);
          }
          else {
            fail($input);
            e.preventDefault();
          }
        }
      })
    });
  });
}

Then you call the plugin like:

$(function() {
  $('#frmReferral').validate();
});
Sign up to request clarification or add additional context in comments.

Comments

0

You could give them all a class for jQuery use through a single selector. Then use your validation function to loop through and handle every case.

$(".validate").each(//do stuff);

Comments

0
    form.submit(function(){
        if(validateCompanyName() && validateHrmanagerName()) // Its logical AND not bitwise
            return true
        else
            return false;

You can do this.

var x = $("input[name^='test-form']").toArray();

for(var i = 0; i < x.length; i++){
  validateCompanyName(x[i]);
 validateHrmanagerName(x[i]);
}

1 Comment

was there supposed to be an end for your submit( ? :D

Your Answer

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.