Unobtrusive validation in MVC – trigger it clientside

using the validation with data annotations

Validating in MVC using data annotations is a wonderful thing, you get to use the same validation rules in both client side and serverside.

How its done – Setting up validation

In the entity file in codebehind

class Model
{
 [Required(ErrorText="This cannot be left empty")]
 public string Name{ get; set}
}

In the front

The below lines depict how an edit field is created and where the validation error message is shown if doesnt validate

   <%= Html.EditorFor(x=> x.Name) %>
   <%= Html.ValidationMessageFor(x=> x.Name) %>

The problem

However there comes scenarios when you don want to call mvc pages the ordinary way but call them with for
example jquery and ajax. In that scenario you need to jack in to the existing unobtrusive validation and then

perform your ajax call. Or you need to use a different validation system altogether, for example jquery validation plugin.

What we want is something like the scenario below

An Example scenario:

  • run validation client side
  • post by using ajax

Trigger client side

In the ordinary data annotation scenario the client side validation is run upon pressing a submit button
We want to intercept that, or better we want to trigger the validation without submitting because we want
submit using jquery ajax

So how do we do that?

var $form = ("#MyForm"); // Select our form with jQuery

var errors;
if ($form[0]['__MVC_FormValidation']) {
errors = $form[0]['__MVC_FormValidation'].validate("submit"); // Validate the form
}
if (!$form[0]['__MVC_FormValidation'] || errors.length == 0) {
// run submit ajax call
}
else
{
// take appropriate action to submit
}

This line is the crucial line. We get hold of the validation object and runs the validation client side without submitting
$form[0][‘__MVC_FormValidation’].validate(“submit”);

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s