Question

After extensive searching on this matter, I have been unable to find an answer on my own for an issue I'm experiencing where the jQuery validation plugin is cannibalizing a character count plugin I'm using for an SMS-via-PHP form.

If you get into the form, on the front-end, and start typing in the text area, the counter works just fine, and of course the validation won't fire since there's text in the element... but, in the interest of testing, if you try to submit the form without a message, the validation fires, and the error message is displayed relative to the textarea, and when you input copy, the validation message goes away, but the character counter no longer works.

Here's the character counter I'm using: http://cssglobe.com/jquery-plugin-simplest-twitterlike-dynamic-character-count-for-textareas/

Here's the way I have my script laid out:

$(function(){
    //irrelevant functions have been omitted

    $("#smsMessage").charCount({
        allowed:110,        
        warning:10, 
    });
    $('form').validate();
});

I even tried re-firing the counter function, as a callback to the validation, but that just resulted in a duplicate, non-functional counter being placed next to the textarea.

$(function(){
    //irrelevant functions have been omitted

    $("#smsMessage").charCount({
        allowed:110,        
        warning:10, 
    });
    $('form').validate({
        invalidHandler: function(form, validator) {
            var errors = validator.numberOfInvalids();
            if (errors) {
                $("#smsMessage").charCount({
                    allowed:110,        
                    warning:10, 
                });
            }
        }
    });
});

Admittedly, this is my first solo webDev project in a while -- it's for my fiancee and my wedding site, so I'm trying to class it up a bit. If there's any way to have the counter and validation play nicely together, that would be great. If not, it's not exactly the end of the world, but it's still less than ideal.

Was it helpful?

Solution

The problem is that your counter plugin is not very smart about keeping track of where the counter is. It creates the counter by putting it after the text area. The validate plugin does the same thing with it's error messages. The easiest fix will be to tell the validate plugin to put it's errors somewhere else. Try this:

$('form').validate({
    errorPlacement: function(error,element){
        if (element.attr('id') == 'smsMessage'){
            error.insertAfter(element.next());
        } else {
            error.insertAfter(element);
        }            
    }       
});​

I made a working example so you can try it out: http://jsfiddle.net/ryleyb/6HKuq/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top