1

I have a custom DateTextBoxControl in mvc 3. The control is used as

@Html.DateTextBoxFor(x => x.ActiveParty.PartyDetail.InUSASince, 
     new { @class = "span-7 data date-picker", @maxlength = 10 })

In model i am adding validation attribute for the property InUSASince as

[RequiredWhen("NationalityId", new object[] { Nationality_USA }, 
                  true, ErrorMessage = "Date Field is Required.")]
public virtual DateTime? InUSASince { get; set; }

I have registered unobtrusive javascript validator as

    $.validator.unobtrusive.adapters.add("requiredwhen", ["dependentproperty",                    
               "expectedvaluefordependentproperty", "reverse"], function (options) 
    {
        var expectedvaluefordependentproperty = null;
        var reverse = options.params.reverse;
        if (options.params.expectedvaluefordependentproperty.length != 0)
        {
             expectedvaluefordependentproperty = options. params.  
                                         expectedvaluefordependentproperty.split(',');
             var prefix = getModelPrefix(options.element.name);
             dependentproperty = options.params.dependentproperty,
             fullOtherName = appendModelPrefix(dependentproperty, prefix),
             element = $(options.form).find(":input[name='" + fullOtherName + "']");
             options.rules["jqRequiredwhen"] = { dependentelement: element, 
                          expectedvaluefordependentproperty:  
                          expectedvaluefordependentproperty, reverse: reverse };
             if (options.message) {
                  options.messages["jqRequiredwhen"] = options.message; }
         }
     });

when I run the page. it is not showing any validation msg. When i took view source. I can see the control has no validation related attributes.

anyone knows what I am missing ?

Thanks.

1 Answer 1

2

At last I figured what is missing. In user control extension for DateTextBoxFor i am not taking the Unobtrusive Validation Attributes defined for the InUSASince property.

to do that we have to use these lines of code.

 ModelState modelState;

    if (htmlHelper.ViewData.ModelState.TryGetValue(fullName, out modelState))
    {
          if (modelState.Errors.Count > 0)
          {
              tagBuilder.AddCssClass(HtmlHelper.ValidationInputCssClassName);
          }
    }

    var attr = htmlHelper.GetUnobtrusiveValidationAttributes(fullName, modelMetaData);
    tagBuilder.MergeAttributes(attr);

This will add validation attributes for the custom control.

I hope this will be useful to some one.

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

Comments

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.