1

Can someone help me with client validation issue (MVC4 RC, VS2010)? The Intellisense is not showing addMethod in jQuery.validator. When I run the application, it throws javascript null error at this method. I want to allow the users to enter the time that is greater than current time. My CustomValidation.js file looks like this:

/// <reference path="jquery-1.7.2-vsdoc.js" />
/// <reference path="jquery.validate-vsdoc.js" />
/// <reference path="jquery.validate.unobtrusive.js" />

jQuery.validator.addMethod('dategreaterthan', function (value, element, param) {   
      var today = new Date();
      return Date.parse(value) > today; 
});

$.validator.unobtrusive.adapters.add("dategreaterthan", function (options) {
    options.rules["dategreaterthan"] = true;
    options.messages["dategreaterthan"] = options.message;
});

Here is the custom validation attribute code:

public class DateGreaterThanAttribute : ValidationAttribute, IClientValidatable
    {
        private const string DefaultErrorMessage = "{0} Time must be greater than current time";

        public DateGreaterThanAttribute() :
            base(DefaultErrorMessage) 
        { }

        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            ValidationResult validationResult = ValidationResult.Success;

            if (((DateTime)value).TimeOfDay >= DateTime.Now.TimeOfDay)
                return validationResult;
            else
            {
                return new ValidationResult(FormatErrorMessage(this.ErrorMessage));                
            }
        }

        public override string FormatErrorMessage(string name)
        {
            return base.FormatErrorMessage(name);
        }


        #region IClientValidatable Members

        public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
             var rule = new ModelClientValidationRule();
             rule.ErrorMessage = FormatErrorMessage(metadata.GetDisplayName());
             rule.ValidationType = "dategreaterthan";
             yield return rule;                
        }

        #endregion
    }

I have added the CustomValidation.js to the BundleConfig.cs file as shown below: public class BundleConfig (not sure if it is correct):

   public static void RegisterBundles(BundleCollection bundles)
    {
        bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
                    "~/Scripts/jquery-1.*"));

        bundles.Add(new ScriptBundle("~/bundles/jqueryui").Include(
                    "~/Scripts/jquery-ui*"));

        bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
                    "~/Scripts/jquery.unobtrusive*",
                    "~/Scripts/jquery.validate*"));

        bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
                    "~/Scripts/modernizr-*"));

        bundles.Add(new StyleBundle("~/Content/css").Include("~/Content/site.css"));

        bundles.Add(new StyleBundle("~/Content/themes/base/css").Include(
                    "~/Content/themes/base/jquery.ui.core.css",
                    "~/Content/themes/base/jquery.ui.resizable.css",
                    "~/Content/themes/base/jquery.ui.selectable.css",
                    "~/Content/themes/base/jquery.ui.accordion.css",
                    "~/Content/themes/base/jquery.ui.autocomplete.css",
                    "~/Content/themes/base/jquery.ui.button.css",
                    "~/Content/themes/base/jquery.ui.dialog.css",
                    "~/Content/themes/base/jquery.ui.slider.css",
                    "~/Content/themes/base/jquery.ui.tabs.css",
                    "~/Content/themes/base/jquery.ui.datepicker.css",
                    "~/Content/themes/base/jquery.ui.progressbar.css",
                    "~/Content/themes/base/jquery.ui.theme.css"));
        bundles.Add(new ScriptBundle("~/bundles/customvalidation").Include(
                    "~/Scripts/CustomValidation.js"));     
    }
3
  • this is probably not the issue, but your validation always returns false Commented Jul 16, 2012 at 14:14
  • It was a typo. I just updated the code. Do you know why it is throwing null error on addMethod? Commented Jul 16, 2012 at 14:37
  • Create a new MVC 4/RC internet app and use F12 tools to understand validation in the account controller/views (register, change password, etc). That way you can figure out why jQuery is not loaded. Commented Jul 16, 2012 at 18:45

1 Answer 1

2

Make sure that you have included the jqueryval bundle (containing ~/Scripts/jquery.unobtrusive* and ~/Scripts/jquery.validate* scripts) before your custom bundle (which you have associated with jqueryui). So in that order:

@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/jqueryval")
@Scripts.Render("~/bundles/jqueryui")
Sign up to request clarification or add additional context in comments.

6 Comments

I just updated both BundleConfig.cs and _Layout.cstml with no luck. @Scripts.Render("~/bundles/jquery") @Scripts.Render("~/bundles/jqueryval") @Scripts.Render("~/bundles/jqueryui") @Scripts.Render("~/bundles/customvalidation") @RenderSection("scripts", required: false)
Sorry I can't repro. This works for me. Can you send me your sample project?
Use the debugger to see what scripts are loaded.
I am not getting error after adding the above jqueryval bundle. However the client validation is still not working. It loaded all scripts correctly. May be I am doing something wrong. I will do more research and report my findings. Thanks!
I have figured it out the root cause of this issue. After adding options.rules["dategreaterthan"] = true; to jQuery.validator.unobtrusive.adapter.add method, the client side validation is working now. Here is the updated method: jQuery.validator.unobtrusive.adapters.add("dategreaterthan", function (options) { options.rules["dategreaterthan"] = true; options.messages["dategreaterthan"] = options.message; });
|

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.