Computer Magic Logo
Implement Client Side Validation

Sunday, November 22, 2015

Published by Aristotelis Pitaridis

The fact that every time a user types wrong information and the form submits the data to the server is not nice. It is better to handle the validation in browser and allow the submission of the information only if they are correct. In order to do it we will have to change the Web.config file and install the jQuery.Validation.Unobtrusive library.

In order to install the library we will use NuGet. We have to display the Package Manager Console by opening the Tools menu and selecting the "Package Manager Console" command from the "Library Package Manager" submenu. The Package Manager Console will appear at the bottom of the Visual Studio window.

In the Package Manager Console we type "Install-Package jQuery.Validation.Unobtrusive" and we press the Enter button in order to execute the command. The library will be installed and a message will appear on the screen informing us about the successful installation of the library.

Now we have to define the required libraries for the client side validation. In order to do it we add the following lines in the header of our HTML page.

<script src="~/scripts/jquery-1.4.1.min.js"></script>
<script src="~/scripts/jquery.validate.min.js"></script>
<script src="~/scripts/jquery.validate.unobtrusive.min.js"></script>

After the change our view has the following contents.

@inherits Umbraco.Web.Mvc.UmbracoTemplatePage
@{
    Layout = null;
}
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>@Umbraco.Field("title")</title>
    <meta name="description" content="@Umbraco.Field("description")">
    <meta name="keywords" content="@Umbraco.Field("keywords")">

    <script src="~/scripts/jquery-1.4.1.min.js"></script>
    <script src="~/scripts/jquery.validate.min.js"></script>
    <script src="~/scripts/jquery.validate.unobtrusive.min.js"></script>
</head>
<body>
    @Html.Action("Index", "ContactFormSurface")
</body>
</html>

We have to type the correct version for the jQuery library that we have installed in our Umbraco installation. We also have to add the following application settings in the Web.config file.

<configuration>
  <appSettings>
    <add key="ClientValidationEnabled" value="true"/>
    <add key="UnobtrusiveJavaScriptEnabled" value="true"/>
  </appSettings>
</configuration>

Now if we try again to see the contact form on a browser and try to submit the form without typing the required information, the browser will display the error messages without submitting the data to the server. The submission will occur only when the user has typed valid information.