-->

Thursday, March 27, 2014

How to Implement Client-Side Validation in ASP.NET MVC

How to Implement Client-Side Validation in ASP.NET MVC

Implementing Client-Side Validation in an Asp.Net MVC application requires some app settings in the web.config file that must be true. These settings are used to enable two jquery i.e. jquery.validate.min.js and jquery.validate.unobtrusive.min.js in our project.

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

These setting are by default enabled in an MVC project so programmer just remember to check these lines if validation are not working at all. In Visual studio there is an in-built validation attribute mostly used in all the required fields.

[Required]
(Field to be required…..)

This attribute is defined in System.ComponentModel.DataAnnotations namespace and it is used to not complete the page submission if user don’t enter any value in the respective field. The error message shown is the standard message ("Required") by default, it can be changed by the programmer by using:

[Required (ErrorMessage = "This field is Required ")]
(Field to be required…..)

After doing the changes in model, in view page programmer have to write the element which shows the error for that specified field.

(Field to be entered)
@Html.ValidationMessageFor("the labda expression for the property")

Some more lines are used by Visual Studio to adds these references automatically on view. It adds following code snippet to the bottom of the view:

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

Run the respected view, don’t insert any value, click on submit then it will show the specified error without submitting the page. This is client validation, when this page submitted and then show errors, it will called server side validation discussed in the next article.

Read other related articles

Also read other articles

© Copyright 2013 Computer Programming | All Right Reserved