views:

1486

answers:

3

On a HTML page I have an inputbox that has a 'watermark' on it when it is empty. (eg: "enter text here..."). Kind of like this: http://digitalbush.com/projects/watermark-input-plugin/ - but custom written.

The problem is that I can't figure out how to validate this field with the jQuery validation plugin (http://docs.jquery.com/Plugins/Validation/) so that it treats my watermark text as if the field was empty.

I can't find an option in the jQuery validator to let me specify a custom rule for when a field is valid, is there one? I could find options that allow me to specify whether a field needs to be validated based on custom logic, but not how it should be validated.

What am I missing?

+4  A: 

Check out this blog post:

http://randomactsofcoding.blogspot.com/2008/10/starting-with-jquery-how-to-write.html

Tells you how to construct a custom validation rule for a field.

Kazar
Thanks, I figured out a solution based on your link.
legenden
+3  A: 

Thanks to Kazar for providing me with the link, I came up with the following solution (if anyone is interested):

    function notWatermark(value, element){
        return value != 'enter text...';
    }

    $.validator.addMethod("notWatermark", notWatermark, "Field cannot be empty.");

    $('#SearchForm').validate({
        rules: {
            SomeField: {
                required: true,
                notWatermark: true
            }
         },
legenden
Just a point - if someone types 'enter text...' into the box, what happens? Perhaps better to have a flag using the class of the element?
Kazar
Your point is correct, but I'm not worried about someone entering enter text... in the textbox. I like the side effect of it not being allowed. :)
legenden
+1  A: 

When using unique watermark labels for each of your testboxes (For example 'enter firstname', 'enter last name'...), you could improve the script to:

function noWatermark(value, element) {
        return value.toLowerCase() != element.defaultValue.toLowerCase();
    }

$.validator.addMethod("noWatermark", noWatermark, "required.");

This also removes the hardcoded text from your script.

Chris