Johnv2020
Johnv2020

Reputation: 2136

mvc3 jquery client custom validation not running

I've been trying to get client side custom validation working for the last two days now on ASP.Net MVC3. I've followed the examples here, here, here and here but cannot get it to run. Could someone take a look at my (current) code and please let me know if you see any errors, any help at all would be greatly appreciated

Web.Config has both ClientValidationEnabled & UnobtrusiveJavaScriptEnabled set true

_Layout.cshtml references files as follows

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

The server side validation class is defined as follows

public class DateFormatValidation : ValidationAttribute, IClientValidatable
{
    public string ValidDateFormat { get; set; }

    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
    {
        var modelClientValidationRule = new ModelClientValidationRule
        {
            ValidationType = "validatedate",  // the name of the validation rule as specified in DateFormatValidator.js
            ErrorMessage = LocalisationStrings.InvalidDateFormat
        };

        modelClientValidationRule.ValidationParameters["name"] = ValidDateFormat;
        yield return modelClientValidationRule;
    }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {            
        var dateString = (string) value;
        if(String.IsNullOrEmpty(dateString))
        {
            return ValidationResult.Success;
        }

        // if we can't convert to a date based on the current culture then we will get a null back from the ConvertLocalDateFormatToISO extension method
        if(String.IsNullOrEmpty(dateString.ConvertLocalDateFormatToISO()))
        {
            return new ValidationResult(LocalisationStrings.InvalidDateFormat);
        }
        return ValidationResult.Success;
    }
}

The view model is defined as follows

public class SearchViewModel : ElectronicDocument
{

    #region Properties

    [DateFormatValidation(ValidDateFormat="validatedate")] // addig the paramter to the attribute is just a test to get this to work
    public string DueDateFrom
    {
        get;            
        set;             
    }

    [DateFormatValidation]
    public string DueDateTo
    {
        get;
        set;             
    }

The client side validation script is as follows:

(function ($) {
$.validator.addMethod('validatedateformat', function (value, element, param) {
    if (!value) { return true; }
    try {
        var isValidDate = false;
        /* - CheckDateValidFormat is available from the base controller class  */
        $.get('CheckDateValidFormat(' + value +')',
            function (data) {                  
                isValidDate = data;
            });
        if (isValidDate) {
            return true;
        }
        return false;
    }
    catch (e) {
        return false;
    }
});

$.validator.unobtrusive.adapters.add('validatedate', ['name'], function (options) {
    options.rules["validatedateformat"] = options.params.name;
    if (options.message) options.messages["validatedateformat"] = options.message;
});

} (jQuery));

Finally the view looks as follows:

<td style="font-size:10px; white-space:nowrap; color: #666">               
           @Html.TextBox("DocumentDateFrom", Model.DocumentDateFrom, new { @class = "date", style = "width:90px;" })
        to @Html.TextBox("DocumentDateTo", Model.DocumentDateTo, new { @class = "date", style = "width:90px;" })</td>

Upvotes: 1

Views: 471

Answers (1)

Jakub Konecki
Jakub Konecki

Reputation: 46008

You are including jquery-1.8.11.min.js. This version of jQuery doesn't exist, as the latest version is 1.7.2.

I suspect you are including jQuery UI (latest version 1.8.20) and you think that's jQuery. Make sure you're using correct files.

Upvotes: 2

Related Questions