Manually set unobtrusive validation error on a textbox

Shawn Mclean picture Shawn Mclean · Sep 11, 2011 · Viewed 24.7k times · Source

I'm doing something similar to the remote validation, except that I already make my calls manually via jquery and setup whatever I had to setup.

Now my problem is, if I want to tell the validator that a particular textbox is not valid (and prevents the page from submitting, highlight the textbox, etc). How would I do this from code?

@Html.LabelFor(m => Model.Slug)
@Html.TextBoxFor(m => Model.Slug)
<span id="UrlMsg" class="field-validation-error" style="display: none;"></span>

 if (error) {
        $('#UrlMsg').html('This name is already in use.').fadeIn('fast');
        //what should I do here for the rest of the validation?
 }

Answer

SkipHarris picture SkipHarris · Nov 3, 2011

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);