0

I'm working on a validation function in jQuery and am getting a bit stuck. I've got a working version that is very lengthy and full of hardcoded form values which I'm trying to avoid. Here's what works, currently:

$(document).ready(function(){
  var fname = $("#formFName");
  var lname = $("#formLName");

  fname.blur(validateFName);
  lname.blur(validateLName);

  function validateFName(){
    if(fname.val().length > 0){
      fname.removeClass("req_error");
      return true;
    }
    else {
      fname.addClass("req_error");
      return false;
    }
  }

  function validateLName(){
    if(lname.val().length > 0){
      lname.removeClass("req_error");
      return true;
    }
    else {
      lname.addClass("req_error");
      return false;
    }
  }
});

That part works fine for those two fields but I'd like to encapsulate the whole thing in a function that's a bit easier to maintain. Something like this:

$(document).ready(function(){

  $("#first_name").blur(validateField("first_name","text"));
  $("#last_name").blur(validateField("last_name","text"));
  $("#email_address").blur(validateField("email_address","email"));

  function validateField(formfield, type){
    var field = $("#" + formfield);
    switch(type) {
      case "text":
        if(field.val().length > 0){
          field.removeClass("req_error");
          return true;
        }
        else {
          field.addClass("req_error");
          return false;
        }
        break;
      case "email":
        var filter = /^[a-zA-Z0-9]+[a-zA-Z0-9_.-]+[a-zA-Z0-9_-]+@[a-zA-Z0-9]+[a-zA-Z0-9.-]+[a-zA-Z0-9]+.[a-z]{2,4}$/;
        if(filter.test(field.val())) {
          field.removeClass("req_error");
          return true;
        else {
          field.addClass("req_error");
          return false;
        }
        break;
    }
  }
});

However, when I do that I get the following error in Firefox's JS error log:

Error: ((f.event.special[r.origType] || {}).handle || r.handler).apply is not a function Source File: /scripts/jquery-1.7.1.min.js Line: 3

A quick Google for that error hasn't yielded anything that means anything to me, unfortunately. I've tried alerts in various spots and doing so has verified that the proper form field names are indeed being passed where there supposed to be, but as I'm fairly new to jQuery (and not great at JavaScript) I'm at a bit of a loss here.

Thanks to anyone who can point me in the right direction. Also, if anyone thinks that I'm going about this in the wrong way, I'm more than happy to change. I tried using the jQuery validation plugin but I'm also using some dynamically created fields and unfortunately the plugin prevents the visitor from submitting the form when hidden required fields are involved.

2 Answers 2

2

Sounds like you could simplify this by attaching behavior instead of specific elements:

<input type="text" id="someId" class="validate-text" />
<input type="text" id="someOtherId" class="validate-email" />

$('.validate-text').live('blur', function()
{
    $(this).removeClass('req_error');
    if($.trim(this.value).length < 1)
       $(this).addClass('req_error');
});

$('.validate-email').live('blur', function()
{
    // Same thing with the email validation logic
});

This way, you dont need to attach specific event handlers to your elements and instead use those handlers to check the behavior you want. Then you simply mark HTML elements with specific classes to mark the validation mode you want.

Assuming I understood your question correctly.

Sign up to request clarification or add additional context in comments.

2 Comments

I love the idea and I had the same thought but had absolutely no idea how to implement this. I've added your code but I can't seem to make it work -- I get no errors in the Error Console, either. Do I need to include $(document).ready(function(){? I've tried with and without to no avail.
Never mind, I'm an idiot. I forgot what class I was looking for...works like a champ and is far more efficient than what I was trying to do. Thanks a bunch!
0

You can't pass a function invocation expression to .blur(). You can pass an anonymous function constructor:

$("#first_name").blur(function () {validateField("first_name","text");});

Or pass the name of a function:

function validateFirstName() {
    validateField("first_name","text");
}

* * *

$("#first_name").blur(validateFirstName));

@Tejs's suggestion to use classes to attach validators is a good one, as well.

1 Comment

David -- thanks to you too, your correction to my code fixed my specific problem but for simplicity's sake I like the validator option.

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.