Manually set unobtrusive validation error on a textbox
First, you can add a validation summary:
@Html.ValidationMessageFor(m => m.Slug)
Then you can manually trigger jQuery validation / unobtrusive validation with the .showError method. Here is a sample:
var errorArray = {};
errorArray["Slug"] = 'Some error message for the Slug text box';
$('#SomeFormId').validate().showErrors(errorArray);
Using showErrors did not allow the error to persist, so that running .valid() cleared the error. Instead, I added a "forcibleerror" rule and a javascript method to set the message.
function forceError(element, errorMessage) {
$(element).rules("add", {
forcibleerror: true,
messages: {
forcibleerror: function () { return errorMessage; }
}
});
var isForced = false;
if (errorMessage) {
isForced = true;
}
$(element)[0].dataset.isForced = isForced;
$(element).valid();
}
$.validator.addMethod("forcibleerror", function (value, element) {
return $(element)[0].dataset.isForced !== "true";
});
Usage:
forceError($('#Slug'), 'my custom message');
To put it back in a valid state:
forceError($('#Slug'), '');
You can also do:
@Html.ValidationMessageFor(m => m.Slug)
With this function in your code:
function setError(id, message) {
var span = $("span[data-valmsg-for=\"" + id + "\"]");
if (span && span.length > 0) {
$(span).html(message);
if (message && message != "") {
$(span).removeClass("field-validation-valid");
$(span).addClass("field-validation-no-valid");
} else {
$(span).removeClass("field-validation-no-valid");
$(span).addClass("field-validation-valid");
}
}
}
Then can set the error
setError("Slug", "errorMsg");