Home > .NET > MVC3 unobtrusive JavaScript validation via HTML5 in Razor – Rocks!

MVC3 unobtrusive JavaScript validation via HTML5 in Razor – Rocks!

November 18, 2010 Leave a comment Go to comments

It sounds daunting I know, full of buzz words, but they are truely some good cool shit once you see it in action!

The Model

using System.ComponentModel.DataAnnotations;
using System.Collections.Generic;

namespace Mvc3Application1.Models
    public class UserModel

        [StringLength(6, MinimumLength = 3)]
        [Display(Name = "User Name")]
        [RegularExpression(@"(\S)+", ErrorMessage = "White space is not allowed")]
        public string UserName { get; set; }

        [StringLength(8, MinimumLength = 3)]
        [Display(Name = "First Name")]
        public string FirstName { get; set; }
        [StringLength(9, MinimumLength = 2)]
        [Display(Name = "Last Name")]
        public string LastName { get; set; }
        public string City { get; set; }


The Controller (Edit)

public ViewResult Edit(string id)
            return View(usrs.GetUser(id));

        public ViewResult Edit(UserModel um)
            if (!TryUpdateModel(um))
                ViewModel.updateError = "Update Failure";
                return View(um);

            return View("Details", um);

Now scaffolds it to

The View (Razor)


@using (Html.BeginForm()) 


  <div class="editor-label">@Html.LabelFor(model =>; model.UserName) </div>

  <div class="editor-field">@Html.EditorFor(model =>; model.UserName) @Html.ValidationMessageFor(model =>; model.UserName) </div>

  <div class="editor-label">@Html.LabelFor(model =>; model.FirstName) </div>

  <div class="editor-field">@Html.EditorFor(model =>; model.FirstName) @Html.ValidationMessageFor(model =>; model.FirstName) </div>

  <div class="editor-label">@Html.LabelFor(model =>; model.LastName) </div>

  <div class="editor-field">@Html.EditorFor(model =>; model.LastName) @Html.ValidationMessageFor(model =>; model.LastName) </div>

  <div class="editor-label">@Html.LabelFor(model =>; model.City) </div>

  <div class="editor-field">@Html.EditorFor(model =>; model.City) @Html.ValidationMessageFor(model =>; model.City) </div>

  <p><input type="submit" /> </p>
</fieldset> } 

Make sure you have the setting switched on

<appsettings><add value="true" key="ClientValidationEnabled" /><add value="true" key="UnobtrusiveJavaScriptEnabled" /></appsettings>

and of course add some javascript refs

 <script src="@Url.Content("~/Scripts/jquery-1.4.1.min.js")" type="text/javascript" />
<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")" type="text/javascript"/>
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"/>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"/>

Now run it!

and see what’s showing in html5 – the magic

<!DOCTYPE html>
    <div class="page">
        <div id="header">
            <div id="title">
                <h1>My MVC Application</h1>
            <div id="logindisplay">
                Login Disabled
            <div id="menucontainer">
                <ul id="menu">
                    <li><a href="/">Home</a></li>
                    <li><a href="/Home/About">About</a></li>
        <div id="main">
<form action="/Home/Edit/BenM" method="post">    
        <div class="editor-label">
            <label for="UserName">User Name</label>
        <div class="editor-field">
            <input class="text-box single-line" data-val="true" data-val-length="The field User Name must be a string with a minimum length of 3 and a maximum length of 6." data-val-length-max="6" data-val-length-min="3" data-val-regex="White space is not allowed" data-val-regex-pattern="(\S)+" data-val-required="The User Name field is required." id="UserName" name="UserName" type="text" value="BenM" />
            <span class="field-validation-valid" data-valmsg-for="UserName" data-valmsg-replace="true"></span>
        <div class="editor-label">
            <label for="FirstName">First Name</label>
        <div class="editor-field">
            <input class="text-box single-line" data-val="true" data-val-length="The field First Name must be a string with a minimum length of 3 and a maximum length of 8." data-val-length-max="8" data-val-length-min="3" data-val-required="The First Name field is required." id="FirstName" name="FirstName" type="text" value="Ben" />
            <span class="field-validation-valid" data-valmsg-for="FirstName" data-valmsg-replace="true"></span>
        <div class="editor-label">
            <label for="LastName">Last Name</label>
        <div class="editor-field">
            <input class="text-box single-line" data-val="true" data-val-length="The field Last Name must be a string with a minimum length of 2 and a maximum length of 9." data-val-length-max="9" data-val-length-min="2" data-val-required="The Last Name field is required." id="LastName" name="LastName" type="text" value="Miller" />
            <span class="field-validation-valid" data-valmsg-for="LastName" data-valmsg-replace="true"></span>
        <div class="editor-label">
            <label for="City">City</label>
        <div class="editor-field">
            <input class="text-box single-line" data-val="true" data-val-required="The City field is required." id="City" name="City" type="text" value="Seattle" />
            <span class="field-validation-valid" data-valmsg-for="City" data-valmsg-replace="true"></span>
            <input type="submit" value="Save" />
    <a href="/">Back to List</a>
            <div id="footer">

Now please note that prior to MVC3, the client-side validation system was decoupled from server-side through json, ie.

which you’ll get the same result in MVC3 when unobtrusive javascript is turned off.

<script type="text/javascript"> 
if (!window.mvcClientValidationMetadata) { window.mvcClientValidationMetadata = []; }
window.mvcClientValidationMetadata.push({"Fields":[{"FieldName":"FirstName","ReplaceValidationMessageContents":true,"ValidationMessageId":"FirstName_validationMessage","ValidationRules":[{"ErrorMessage":"The FirstName field is required.","ValidationParameters":{},"ValidationType":"required"}]},{"FieldName":"LastName","ReplaceValidationMessageContents":true,"ValidationMessageId":"LastName_validationMessage","ValidationRules":[{"ErrorMessage":"The LastName field is required.","ValidationParameters":{},"ValidationType":"required"},{"ErrorMessage":"The field LastName must be a string with a maximum length of 60.","ValidationParameters":{"max":60},"ValidationType":"length"}]},{"FieldName":"Age","ReplaceValidationMessageContents":true,"ValidationMessageId":"Age_validationMessage","ValidationRules":[{"ErrorMessage":"The field Age must be between 1 and 130.","ValidationParameters":{"min":1,"max":130},"ValidationType":"range"},{"ErrorMessage":"The Age field is required.","ValidationParameters":{},"ValidationType":"required"},{"ErrorMessage":"The field Age must be a number.","ValidationParameters":{},"ValidationType":"number"}]}],"FormId":"form0","ReplaceValidationSummary":true,"ValidationSummaryId":"validationSummary"});
  1. thangnv
    November 30, 1999 at 10:00 am

    oh…thanks you! Article very nice ^^

  1. January 3, 2011 at 11:27 am

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 )

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s

%d bloggers like this: