Eagerly Performing ASP.NET MVC 3 Unobtrusive Client Side Validation
Introduction:
Unobtrusive client side validation is
one of the great feature that I like in ASP.NET MVC
3. Unobtrusive client side validation feature uses the
famous jQuery validation plug-in internally. Jquery
validation plug-in perform client side validation
lazily. What does this means? This simply means that before
submitting the form for the first time, the user can tab
through fields without getting any error message. This makes
sense and lot of developers and designers like this
behavior. But guys coming from places where validation is
performed when fields focus out, may not like this
behavior. In this article, I will show you how to perform
validation on fields when fields focus out.
Description:
Firstly, let's see the default behavior in action. Create a new ASP.NET MVC 3 application. Then just open(or create) HomeController.cs file and add the following code,
1 |
public
ActionResult Index()
|
2 |
{
|
3 |
return
View();
|
4 |
}
|
Next create a new class file UserInformation.cs inside Model folder and add the following code,
01 |
public
class
UserInformation
|
02 |
{
|
03 |
public
int
Id { get; set; }
|
04 |
05 |
[Required(ErrorMessage = "First Name is required")]
|
06 |
[StringLength(10, ErrorMessage = "First Name max length is 10")]
|
07 |
public
string
FirstName { get; set; }
|
08 |
09 |
[Required(ErrorMessage = "Last Name is required")]
|
10 |
[StringLength(10, ErrorMessage = "Last Name max length is 10")]
|
11 |
public
string
LastName { get; set; }
|
12 |
13 |
[Required(ErrorMessage = "Email is required")]
|
14 |
[RegularExpression(@"^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$", ErrorMessage = "Email Format is wrong")]
|
15 |
public
string
Email { get; set; }
|
16 |
}
|
Next open(or create) Index view and add the following lines,
01 |
<%@ Page Language="C#"
Inherits="System.Web.Mvc.ViewPage<EagerlyPerformingValidation.Models.UserInformation>" %>
|
02 |
03 |
<!DOCTYPE html>
|
04 |
05 |
<html>
|
06 |
<head
runat="server">
|
07 |
<title>Index</title>
|
08 |
<link
href="<%: Url.Content("~/Content/Site.css") %>" rel="stylesheet"
type="text/css" />
|
09 |
</head>
|
10 |
<body>
|
11 |
<script
src="<%: Url.Content("~/Scripts/jquery-1.4.4.min.js") %>"
type="text/javascript"></script>
|
12 |
<script
src="<%: Url.Content("~/Scripts/jquery.validate.min.js") %>"
type="text/javascript"></script>
|
13 |
<script
src="<%: Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")
%>" type="text/javascript"></script>
|
14 |
15 |
<% using (Html.BeginForm()) { %>
|
16 |
<%: Html.ValidationSummary(true)
%>
|
17 |
<fieldset>
|
18 |
<legend>UserInformation</legend>
|
19 |
20 |
<%: Html.HiddenFor(model => model.Id)
%>
|
21 |
22 |
<div
class="editor-label">
|
23 |
<%: Html.LabelFor(model =>
model.FirstName) %>
|
24 |
</div>
|
25 |
<div
class="editor-field">
|
26 |
<%: Html.EditorFor(model =>
model.FirstName) %>
|
27 |
<%: Html.ValidationMessageFor(model =>
model.FirstName) %>
|
28 |
</div>
|
29 |
30 |
<div
class="editor-label">
|
31 |
<%: Html.LabelFor(model =>
model.LastName) %>
|
32 |
</div>
|
33 |
<div
class="editor-field">
|
34 |
<%: Html.EditorFor(model =>
model.LastName) %>
|
35 |
<%: Html.ValidationMessageFor(model =>
model.LastName) %>
|
36 |
</div>
|
37 |
38 |
<div
class="editor-label">
|
39 |
<%: Html.LabelFor(model => model.Email)
%>
|
40 |
</div>
|
41 |
<div
class="editor-field">
|
42 |
<%: Html.EditorFor(model =>
model.Email) %>
|
43 |
<%: Html.ValidationMessageFor(model =>
model.Email) %>
|
44 |
</div>
|
45 |
46 |
<p>
|
47 |
<input
type="submit"
value="Save"
/>
|
48 |
</p>
|
49 |
</fieldset>
|
50 |
<% } %>
|
51 |
52 |
<div>
|
53 |
<%: Html.ActionLink("Back to List",
"Index") %>
|
54 |
</div>
|
55 |
</body>
|
56 |
</html>
|
Now just run this application. You will see jQuery validation plug-in perform client side validation lazily, i.e, users can tab through fields without getting any error message before submitting the form for the first time. Now for performing validation eagerly, i.e, performing validation each time when users fields focus out, you need to add this script at bottom of the page.
1 |
<script type="text/javascript">
|
2 |
$(document).ready(function
() {
|
3 |
$('input','form').blur(function
() {
|
4 |
$(this).valid();
|
5 |
});
|
6 |
});
|
7 |
</script>
|
Update: There is another way which I feel better and simple,
1 |
<script type="text/javascript">
|
2 |
$(document).ready(function
() {
|
3 |
var
settngs = $.data($('form')[0], 'validator').settings;
|
4 |
settngs.onfocusout = function
(element) { $(element).valid(); };
|
5 |
});
|
6 |
</script>
|
Now, just run your application again. You will see the validation behavior become eager. Now, let's say that you need to add this behavior to all of your views. Adding this script to all of your views may be pain for you. For making this behavior possible in all of your views without adding this script to every view, you need to open jquery.validate.unobtrusive(.min).js file and then replace this script,
1 |
options: { // options structure passed to jQuery
Validate's validate() method
|
2 |
errorClass: "input-validation-error",
|
3 |
errorElement: "span",
|
4 |
errorPlacement: $.proxy(onError, form),
|
5 |
invalidHandler: $.proxy(onErrors,
form),
|
6 |
messages: {},
|
7 |
rules: {},
|
8 |
success: $.proxy(onSuccess, form)
|
9 |
},
|
with this script,
01 |
options: { // options structure passed to jQuery
Validate's validate() method
|
02 |
errorClass: "input-validation-error",
|
03 |
errorElement: "span",
|
04 |
errorPlacement: $.proxy(onError, form),
|
05 |
invalidHandler: $.proxy(onErrors,
form),
|
06 |
messages: {},
|
07 |
rules: {},
|
08 |
success: $.proxy(onSuccess, form),
|
09 |
onfocusout: function
(element) { $(element).valid(); }
|
10 |
},
|
Summary:
By default, ASP.NET MVC 3 leverage
the famous jQuery validation plug-in to perform client side
validation. This famous validation plug-in lazily perform
client side validation. Lot of peoples like this behavior
but many people do not. In this article, I showed you how
you can make the client side validation eager. I am also
attaching a sample application. Hopefully you will enjoy
this article too.