Using jQuery Validation and Field Hinting at the Same TIme

987 views Asked by At

I am trying to use the jQuery Validation plugin (http://docs.jquery.com/Plugins/Validation/) in conjunction with field hinting.

The problem is that the field hinting puts text in the value attribute, and since there's text in the value attribute, the Validation plugin doesn't see that anything is wrong.

My thought was to have the validation throw an error if the field is empty OR if the field contains the same text as the field hint (ie: if someone were to enter "First Name" in the first name field, then an error would result.

Is there an elegant way to use validation in conjunction with code hinting?

Thanks!

Doron

1

There are 1 answers

3
David Tang On

There are two kinds of "hinting" code (better known as a watermark or placeholder text): those that replace the value of a field and those that position some sort of element over the input to look as if the text is inside the input.

I presume you're using the first kind, so one simple (and best) solution is to avoid these kinds entirely, and switch to a plugin that employs the second method. There are a lot of plugins that work this way, such as this one, just be sure to read how they operate.

If changing the hinting code is not an option, then you have two other alternatives. Both are not ideal, but perhaps one will suit you more:

Clear values on submit

Within the hinting code, bind to the submit event of the form, and loop through all inputs to clear any that has the same value as the hint.

The problem with this method is that it must be executed before the validation plugin is initialised. It also won't work for validating fields as you type. You'll also have to check the inputs again after validation to put the hint text back.

Overide .val()

Since the validation plugin uses jQuery, you can overide jQuery's .val() function to return '' if the value is equal to the hint:

var oldVal = $.fn.val;
$.fn.val = function () {
    var returnVal = oldVal.call(this);
    if (returnVal == hintVal) returnVal = '';
    return returnVal;
};

The obvious downside of this is that the plugin must always use .val() to retrieve input values.