Jquery validate and default text
I am trying to find a way to easily add default values to form which is using jquery validate plugin. I searched and didn't find anything useful, and the last similar question is one year old. So, to ask again, is there easy way to add default values to form without messing with jquery validate code. And of course, default values should disappear when user start to type inside the field.
Edit: I see that question is little confusing, so here is better explanation. I want to add default text to form, and i want validation plugin to ignore that default value. I know i can add method that will check if value is default value, but since form is really big, i would prefer some other solution. Like some plugin that places default text 开发者_开发知识库above input field, so if form gets submitted with that filed not filled by user, it appears to validate plugin as empty.
If you just use that as attractiveness, you can just use placeholder attribute, <input name="search" type="text" placeholder="Enter some keywords..." />
If you are talking about the message that is seen after validation fails then you can do something like this. If you are talking a default value for the textbox itself look at the answer from @Caimen.
$("form").validate({
rules: {FirstName: "required defaultCheck"},
messages: {
FirstName: "First name is required"
)};
Even though you've selected your answer this might help someone. If you want the validator to ignore the default text which is what I think you wanted all along you can do this.
$.validator.addMethod(
'defaultCheck', function (value, element) {
if (element.value == element.defaultValue) {
return false;
}
return true;
});
<input type="text" name="user" id="user" value="YOUR DEFUALT VALUE" />
or
$("#user").attr("value", "YOUR DEFAULT VALUE");
Just use the above code in dom ready and it should be fine I would think.
Expanding on previous answer:
HTML:
<input type="text" name="user" id="user" value="YOUR DEFUALT VALUE" />
You should not clear default values from form fields.
This is how I would do it:
<input name="firstName" value="First Name" defaultValue="First Name">
and then in the validation:
if(object.value != object.defaultValue)
// validation
精彩评论