1

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>
6
  • Should that first return false be in the 'client-side validation script'? Surely it will never reach the code underneath beginning with try as it's unreachable? Commented May 28, 2012 at 15:02
  • sorry - I added that just to check if the script was getting run at all, removed now - still no improvement Commented May 28, 2012 at 15:07
  • Where is the code that contains the action CheckDateValidFormat and can you see it being hit in your development IDE Commented May 28, 2012 at 15:15
  • @SpaceBison - nope CheckDateValidFormat is never hit Commented May 28, 2012 at 15:24
  • So I reckon the route to your controller action in the $.get is wrong - if you switch to $.ajax and add an error: function() { etc etc } block it might help you work out what the issue exactly is, if not immediately obvious, but I think you need /area/controller/action or something along those lines. Commented May 28, 2012 at 15:35

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Jakub - I've updated that now to 1.7.2 but still no go

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.