The accepted answer has two big problems that make it useless, in my opinion:
- It doesn't change the input's state to invalid. Therefore, the user is free to submit the form.
- It will be wiped out as soon as the input is validated next, such as on the input's next keyboard event.
kevinpo's answer addresses both of these problems and is probably what you should use if you need dynamically-generated error messages. But static error messages are usually good enough, so...
Let's make this really simple this with unobtrusive validation.
Add this to your site-wide javascript file:
$.fn.extend({
toggleOk: function (value) {
this[0].dataset.ok = value;
this.valid();
}
});
$.validator.addMethod("ok", function (value, element) {
return this.optional(element) || $(element)[0].dataset.ok === "true";
});
$.validator.unobtrusive.adapters.addBool("ok");
Add this to the relevant input element in your HTML. The first attribute, data-val-ok
, tells unobtrusive validation to activate this type of validation for this input and tells it what error message to show when it is invalid. The second attribute, data-ok
, sets the initial state to valid.
data-val-ok="That item does not exist." data-ok="true"
Call this code in your page's Javascript to set the input to invalid, display the error and related formatting, and block page submission.
$('#myInput').toggleOk(false);
Call this to change it back to valid, hide the error and related formatting, and permit page submission:
$('#myInput').toggleOk(true);