In this article I will walk you through the steps of implementing validation in the ASP.NET 5 MVC project using jquery.validate.unobtrusive.js

What is Unobtrusive JavaScript?

Unobtrusive JavaScript is the best practices to separate the JavaScript code from presentation or html.

For example
<input type=”button”
id=”btn”
onclick=”alert(‘hello world’)“
/>

The above code is obtrusive as we have called the JavaScript alert method within the html control’s input tag. In order to make this unobtrusive we can create a separate JavaScript file and with the help of jQuery we can register a click event for this button like this.

$(document).ready(function () {
$(‘#btn’).click(function (e) {
    alert(‘hello world’);
}
});

For validation there is a JavaScript named jquery.validate.unobtrusive.js which can automatically attach validation with all the input controls that you have in your html file. But those controls should have data-val attribute to true. Otherwise the validation for that particular control does not applied. By default, when we use these methods in our code, depending on the data annotation attributes we have used in our Model it automatically applies the validation at the time of rendering the html control.

For example. If our model is:

public
class
Person : Message
{
[GridColumn("Id", true)]
public
int Id { set; get; }
[Required]
[GridColumn("Name", false)]
[StringLength(10, ErrorMessage="Length cannot exceed to 10 character")]
public
string Name { set; get; }
}

In ASP.Net MVC we can associate a model while adding a view and in that view we can call HTML helper functions like this
@Html.EditorFor(model => model.Name)

This will generates an html as follows

<input data-val=”true” data-val-length=”Length cannot exceed to 10 character” data-val-length-max=”10″ data-val-required=”The Name field is required.” id=”Name” name=”Name” type=”text” value=”Ovais” />

1. You can see that depending on the model it has automatically added the data-val-* properties in the html. You have to add a jquery.validation.unobtrusive.js in your project.

2. Then add the file path in the bundle like this:

bundles.Add(new
ScriptBundle(“~/bundles/jqueryval”).Include(
“~/Scripts/jquery.validate*”)); 

3. Then add the script reference in the page as within the script section like this.

@section scripts{
@Scripts.Render(“~/bundles/jqueryval”)

}

4. Make sure you have controls place inside a form.

Handling validation in AJAX calls

When using server side post back in ASP.Net MVC validation works smooth. But for example if you want to invoke some AJAXified request on any button click and wanted to know if the form is validated or not you can add a code like this.

$(‘#Save’).click(function (e) {
var $val = $(this).parents(‘form’);
if (!($val.valid()))
return
false;
else alert(‘form have no errors’);

}