Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Client side validation for custom annotation Asp.Net MVC 4

I am referring this article:

http://haacked.com/archive/2009/11/19/aspnetmvc2-custom-validation.aspx

which shows how to create custom annotation in Asp.Net MVC 2. However, the client side validation scripts, especially "MicrosoftMvcJQueryValidation" is not available in Asp.Net MVC4. I read it on one article it is part of Asp.Net Futures project. I want to hook up my client side validation using Jquery. In my project template script's folder, I see scripts named:

jquery.validate.min.js
jquery.validate.unobtrusive.min.js
jquery.unobtrusive-ajax.min.js

Is there any way I can make use of these existing scripts? or do I have to compulsorily download futures project?

like image 530
Tim Tom Avatar asked May 19 '12 14:05

Tim Tom


People also ask

How can use client-side validation in ASP.NET MVC?

Firstly, you just need to create an ASP.NET MVC application. To create a new ASP.NET MVC application, Open Visual Studio choose File, New, then Project. It will open a New Project window, from where you need to choose node Visual C# and then Web and from the right pane you need to choose ASP.NET Web Application.

What are the steps required to use custom validation annotation?

To create a custom constraint, the following three steps are required: Create a constraint annotation. Implement a validator. Define a default error message.

What is the use of ModelState in MVC?

The ModelState has two purposes: to store and submit POSTed name-value pairs, and to store the validation errors associated with each value.


1 Answers

That article is specific to MVC 2 which used MicrosoftAjax. MVC 4 no longer includes the MS Ajax files as they have been deprecated and the preferred method is to use jquery.

To verify your settings, make sure these scripts are in your layout

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script>

And these two settings are present in the appSettings section in your web.config file

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

So when you add data annotations to your ViewModels you get client side and server side validation both

public class MyModel 
{
    [Required]
    [StringLength(30)]
    public string FirstName { get; set; }

    [Required]
    [StringLength(30)]
    public string LastName { get; set; }
}

In your view just make sure you have code like this

<div>
    @Html.LabelFor(model => model.FirstName)
</div>
<div>
    @Html.TextBoxFor(model => model.FirstName) <br/>
    @Html.ValidationMessageFor(model => model.FirstName)
</div>

<div>
    @Html.LabelFor(model => model.LastName)
</div>
<div>
    @Html.TextBoxFor(model => model.LastName) <br/>
    @Html.ValidationMessageFor(model => model.LastName)
</div>

Update

Here's an example of a custom validator that I have called RateRequiredIfCustomIndexRate This is the javascript side of it so that it gets added to jquery validation

$("document").ready(function () {

    var isCustomRateRequired = document.getElementById("IsCustomRateRequired");

    isCustomRateRequired.onchange = function () {
        if (this.checked) {
            $('#Rate').attr('disabled', 'disabled');
            $('#Rate').val('');
        }
        else {
            $('#Rate').removeAttr('disabled');
        }
    };
});

jQuery.validator.addMethod("raterequiredifcustomindexrate", function (value, element, param) {
    var rateRequired = $("#CustomRateRequired").val();
    if (rateRequired && value == "") {
        return false;
    }
    return true;
});

jQuery.validator.unobtrusive.adapters.addBool("raterequiredifcustomindexrate");
like image 159
CD Smith Avatar answered Nov 14 '22 09:11

CD Smith