I'm building a simple form for my client and They want to display the error message in the text field. Would this be possible to achieve this with jQuery's Validation plugin?
Thanks!
I'm building a simple form for my client and They want to display the error message in the text field. Would this be possible to achieve this with jQuery's Validation plugin?
Thanks!
Quote OP:
"They want to display the error message in the text field. Would this be possible to achieve this with jQuery's Validation plugin?"
Yes. It's possible Use the plugin's errorPlacement
callback function/option.
NO, I would never do it. This makes it nearly impossible for the user to properly interact with the form. The error wipes out any data the user already entered and the user has to delete the text of the message to enter their data. I'm sure you can think of clever ways to overcome these issues, but IMO, it's a really poor design from a UI perspective. Show your client this demo, then scroll down and show them my second demo.
DEMO: http://jsfiddle.net/6fUTV/
$(document).ready(function () {
$('#myform').validate({ // initialize the plugin
// rules & options,
errorPlacement: function(error, element) {
element.val(error.text());
}
});
});
EDIT: Instead you could use the placeholder
attribute. The message will still be inside of the input element, but it will not be seen as a value
so it will not interfere with user interaction as much. However, the big downside to this approach is that if you have a rule to validate the data format such as email
, minlength
, etc... the user will never see the validation message because there is a value sitting inside the field on top of the placeholder!
errorPlacement: function(error, element) {
element.attr("placeholder", error.text());
}
DEMO 2: http://jsfiddle.net/n5saemj7/
Alternatives:
Show errors using message bubbles: http://jsfiddle.net/kyK4G/
More info: How to display messages from jQuery Validate plugin inside of Tooltipster tooltips?
They told you that is a bad method, maybe it is.
But you can use placeholder, instead of replace the content already in, just change this:
errorPlacement: function(error, element) {
element.val(error.text());
}
For this:
errorPlacement: function(error, element) {
element.attr("placeholder",error.text());
}
Hope that helped you, take care !
Yes ofcourse this is possible as you validate the text field and its caught in error simply assign the error msg as value of that text field or placeholder also.
$("#yourtextfield").val("This field can't be empty.");
Yes you can. Your skills seem very raw.
Let's take the simple path because your question sounds simple. On error, give a condition to assign the message string as a value to the input field.
something like
var err = "err_msg";
$('#elementId').val(err);
See the section .val('value')
at http://api.jquery.com/val/