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
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.
Not sure how the validation plugin works, but this is a separate module that is usable.
var SetWatermark = function( oElemToWatermark, sWatermark )
{
var CheckFocus = function(oEvent)
{
var oElem = $(this);
if ( oElem.val() == oElem.data("Watermark") )
oElem.val("").css("color", "");
}
var CheckBlur = function(oEvent)
{
var oElem = $(this);
if ( oElem.val().length == 0 )
oElem.val( oElem.data("Watermark") ).css("color", "Grey");
}
// HTML5 (simple route)
if ( oElemToWatermark[0].placeholder != undefined )
oElemToWatermark[0].placeholder = sWatermark;
// pre HTML5 (manual route)
else if (oElemToWatermark.data("Watermark") == undefined)
oElemToWatermark .data("Watermark", sWatermark)
.val(sWatermark)
.on("focus", CheckFocus )
.on("blur", CheckBlur );
}
var GetWatermarkText = function(oElem)
{
if (oElem[0].plaeholder != undefined)
return oElem[0].placeholder;
else if ( oElem.data("Watermark") != undefined )
return oElem.data("Watermark");
else
{
alert("The element " + oElem[0].id + " does not have a Watermark value.");
return "";
}
}
var GetWatermarkValue = function(oElem)
{
var sVal = oElem.val();
var sWatermark = oElem.data("Watermark");
if (oElem[0].placeholder != undefined
|| sWatermark == undefined
|| sWatermark != sVal)
return sVal;
else if (sVal == sWatermark)
return "";
}
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
}
},
I'm using the Watermark plugin for jQuery, but my situation was similar:
http://code.google.com/p/jquery-watermark/
It uses a classname for the display of the watermark. (I'm not sure if the DigitalBrush version uses a class or not.) I've modified the above function to use jQuery's hasClass() function to determine whether or not the field is evaluated as "empty" based on currently assigned classes.
function notWatermark(value, element){
return !$(element).hasClass("waterMarkClass");
}
$.validator.addMethod("notWatermark", notWatermark, "Required.");
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.