ASP.Net MVC 3 validation on AjaxForm

Yorgo picture Yorgo · May 9, 2011 · Viewed 7.8k times · Source

I have an ajax form on razor view engine. For validation i use dataanotation classes. Validation work fine when user submit the form, validation messages work fine. The problem is, validation wont work on keyup or blur events.

How can i activate validation without submit on ajaxform(ajax.beginform)

Here is my view code:

@using (Ajax.BeginForm(new AjaxOptions { InsertionMode = InsertionMode.Replace,       
        UpdateTargetId = "employeeDetail", HttpMethod = "Post", OnComplete = "Complete", 
        Confirm = "Confirm?" }))
{
    @Html.TextBoxFor(model => model.Email)
    @Html.ValidationMessageFor(model=>model.Email)
    <span style="float:right"><input type="submit" class="tableGenelButton" id="submitButton" value="Kaydet" /></span>
}

Model:

  [RequiredWithMessage]
  [Display(Name = "E-Mail")]
  public string Email { get; set; }

Answer

fretje picture fretje · May 9, 2011

Update:

Ok, apparently you're using Ajax.BeginForm which uses MicrosoftAjax in stead of jQuery (I didn't realize that before). This one needs some extra work to enable client side validation:

You need

<% Html.EnableClientValidation(); %> 

Somewhere in your page, and also links to MicrosoftAjax.js, MicrosoftMvcAjax.js and MicrosoftMvcValidation.js

Here's a link that might be interesting for you:

ASP.NET MVC Client Side Validation With Ajax.BeginForm


To enable client side validation for a custom validation attribute (I guess [RequiredWithMessage] is one of those), you have to implement the IClientValidatable interface.

Here is an article that explains how to do that:

The Complete Guide To Validation In ASP.NET MVC 3 - Part 2