我正在使用jquery validate插件和自定义验证器。
我想将错误消息用作工具提示,以便它显示在焦点上。下面的代码执行此操作,但由于该字段不是必需的,我需要错误消息(工具提示)隐藏,如果值为空或模糊的默认值。
$.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>