Client side validation for custom annotation Asp.Net MVC 4

16,708

Solution 1

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");

Solution 2

The key thing missing here is that the server-side validator must implement the IClientValidatable interface:

public class RateRequiredIfCustomIndexRateAttribute : ValidationAttribute, IClientValidatable
{
    public override bool IsValid(object value)
    {
        return false;
    }

    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
    {
        yield return new ModelClientValidationRule
        {
            ErrorMessage = this.ErrorMessage,
            ValidationType = "raterequiredifcustomindexrate"
        };
    }
}

Once you do that, the client-side validation should be hooked up properly. You can verify this by making sure that your input field has an attribute "data-val-raterequiredifcustomindexrate" attribute.

Share:
16,708

Related videos on Youtube

Tim Tom
Author by

Tim Tom

Updated on September 15, 2022

Comments

  • Tim Tom
    Tim Tom about 1 year

    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?

    • RickAndMSFT
      RickAndMSFT over 11 years
      Google "MVC 3 custom validation" and you'll find several articles like msdn.microsoft.com/en-us/… and tdryan.blogspot.com/2010/12/aspnet-mvc-3-custom-validation.h‌​tml
    • RickAndMSFT
      RickAndMSFT over 11 years
      read the response below any my tutorials. It's not difficult to update them for MVC 4. The concepts are the same.
    • garfbradaz
      garfbradaz about 11 years
      @TimTom no need to sound rude in your comment to Rick. He took the time to reply to your question, even if you you feel it wasnt the correct answer.
  • Tim Tom
    Tim Tom over 11 years
    So how do I hook up my client validation with these scripts? Any tutorial? article?
  • CD Smith
    CD Smith over 11 years
    That's easy, you get it for free :-) when you decorate your ViewModel classes with data annotations, those same rules get translated to client side rules.. updating my answer now
  • Tim Tom
    Tim Tom over 11 years
    Is that really possible? This is my custom validation annotation. I have extended using ValidationAttribute How does my C# code server side validation get translated automatically to Jquery language? I am curious.
  • CD Smith
    CD Smith over 11 years
    Custom validation is different, you also have to add that custom validator to the jquery validation... updating answer again...
  • Tim Tom
    Tim Tom over 11 years
    This is not what I am looking for. The article that I posted in my question is about custom validation not these built in types.
  • CD Smith
    CD Smith over 11 years
    Basically, you add the rule to the validator and the error message will get shown. In my case, I am also enabling/disabling a field based in the rule result.