1

I wrote a simple custom validator. It works on form submission, but not real-time on the client side like I think it should. Is this code correct? Is there something I need to do on the View? For the record, the other (built-in) validators work on the client side. I even added

@{
    Html.EnableClientValidation(true);
    ViewBag.Title = "CaseVue | Patient";
}

to the top of the view. Here's my validator code:

public class BirthDateRangeAttribute : ValidationAttribute, IClientValidatable
{
    public int MaxAge { get; set; }

    public BirthDateRangeAttribute()
    {
    }

    public override bool IsValid(object value)
    {
        string val = value.ToString();
        if (!string.IsNullOrWhiteSpace(val))
        {
            DateTime dt;
            if (DateTime.TryParse(val, out dt))
            {
                return dt >= DateTime.Now.AddYears(MaxAge * -1) && dt <= DateTime.Now;
            }
            else
            {
                return false;
            }
        }
        return false;
    }

    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
    {
        ModelClientValidationRule rule = new ModelClientValidationRule { 
            ErrorMessage = this.ErrorMessage,
            ValidationType = "birthdaterange"
        };
        rule.ValidationParameters.Add("maxage", this.MaxAge);
        yield return rule;
    }
}

Anyone see what I'm doing wrong?

Vic F
  • 1,143
  • 1
  • 11
  • 26
  • 3
    You are missing the last step, which is adding javascript for your custom validation attribute. See this SO post: http://stackoverflow.com/questions/19726404/client-side-validation-in-custom-validation-attribute-asp-net-mvc-4 – wooters Sep 21 '15 at 19:27
  • 1
    So, the built-in validations have their own JavaScript somewhere? Do you know where? I'm not seeing the reference anywhere on the page, but those client-side validations work fine. – Vic F Sep 21 '15 at 21:28
  • 1
    @VicF, They are in the `jquery.validate.js` (defines the rules etc) and `jquery.validate.unobtrusive.js` (adds the rules based on the `data-val` attributes). Refer [this article](http://www.devtrends.co.uk/blog/the-complete-guide-to-validation-in-asp.net-mvc-3-part-2) for more detail on adding your scripts for client side validation –  Sep 21 '15 at 22:22

0 Answers0