I am using the jquery validate plugin with a custom validator.
I would like to use the error message as a tooltip so it appears on focus. The code below does this, but as the field is not required I need the error message (tooltip) to hide if the value is nothing or the default value on blur.
$.validator.addMethod("showOnfocus", function(value, element) {
var re = new RegExp(/^([FG]?\d{5}|\d{5}[AB])$/);
return value !== element.defaultValue && re.test(value);
});
$("#myform").validate({
debug: true,
rules: {
field: {
showOnfocus: true
}
},
messages: {
field: {
showOnfocus: "This message will act as a tooltip"
}
},
success: function(label) {
label.text("Good result!");
},
submitHandler: function() {
alert("submitted!");
}
});
//I WOULD LIKE TO THINK SOME OF THIS COULD BE INCLUDED IN THE VALIDATE CODE ABOVE - NOT SURE HOW THOUGH
$("#field").focus(function() {
if ($(this).val() == $(this).prop("defaultValue")) {
$(this).val("");
}
$(this).valid();
});
$("#field").blur(function() {
if ($(this).val() == "") {
$(this).val($(this).prop("defaultValue"));
}
});
$("#field").keyup(function() {
$(this).valid();
});
html:
<form id="myform">
<input class="left" id="field" name="field" value="hello" defaultValue="hello" />
<br/>
<input type="submit" value="Validate!" />
</form>