0

I am using data annotations for client side validations. I have two scenarios where I am using [Required] and [RequiredIfTrue]. Issue is my conditional validations are not working.

Working:

Model:

[DisplayName(@"Custom Email Confirmation Address")]
[EmailAddress(ErrorMessage = @"Invalid Email Address")]
public string CustomEmailConfirmationAddress { get; set; }

View:

<div>
    <%=Html.RequiredLabelFor(m => m.CustomEmailConfirmationAddress) %>
    <%=Html.TextBoxFor(m => m.CustomEmailConfirmationAddress, new { maxlength = 100 })%>
    <%=Html.ValidationMessageFor(m => m.CustomEmailConfirmationAddress)%>
</div>

NOT Working:

Scenario = If ShowConceptOptInMessage is checked than make ConceptEmailOptInMessage and PrivacyPolicy field required.

Model:

[DisplayName("Show Concept Opt-In Message")]
public bool ShowConceptOptInMessage { get; set; }

[RequiredIfTrue("ShowConceptOptInMessage", ErrorMessage = "Concept Email Opt-In Message is required")]
[DisplayName("Concept Email Opt-In Message")]
public string ConceptEmailOptInMessage { get; set; }

[RequiredIfTrue("ShowConceptOptInMessage", ErrorMessage = "Concept Privacy Policy is required")]
[DisplayName("Concept Privacy Policy")]
public string PrivacyPolicy { get; set; }

View:

<div>
    <%=Html.LabelFor(m => m.ShowConceptOptInMessage) %>
    <%=Html.CheckBoxFor(m => m.ShowConceptOptInMessage)%>
    <%=Html.ValidationMessageFor(m => m.ShowConceptOptInMessage)%>
</div>

 <div>
    <%=Html.LabelFor(m => m.ConceptEmailOptInMessage) %>
    <%=Html.TextAreaFor(m => m.ConceptEmailOptInMessage, new { maxlength = 1000 })%>
    <%= Html.ValidationMessageFor(m => m.ConceptEmailOptInMessage)%>
</div>

<div>
    <%=Html.LabelFor(m => m.PrivacyPolicy) %>
    <%=Html.TextAreaFor(m => m.PrivacyPolicy)%>
    <%= Html.ValidationMessageFor(m => m.PrivacyPolicy)%>
</div>

Controller method for both scenario:

Controller:

[HttpPost]
public ActionResult Edit(ConceptConfigurationModel model)
{
    try
    {
        if (this.ModelState.IsValid)
        {
            // model
            this.ConceptManager.SaveConcept(model);
            model.Submitted = true;
        }
    }
    catch (BusinessLogicException ex)
    {
        this.ModelState.AddModelError("ConceptName", ex.Message);
    }
    ModelState.Clear();
    this.ConceptManager.FillConceptModel(model);

    return View(model);
}
1
  • Not sure why you have accepted an answer which has nothing to do with your problem and is just an awful hack. Assuming your using the foolproof [RequiredIfTrue] and you have included the relevant scripts, then your code works fine. Commented Apr 12, 2016 at 1:10

1 Answer 1

1

With ASP.NET MVC 4, RequiredIf is not working, I have achieved the same using jquery unobtrusive , add the below javascript method

function AddValidation()
{
var showConceptOptInMessage = $("#ShowConceptOptInMessage").val();
  if(showConceptOptInMessage)
{
  $("#ConceptEmailOptInMessage").attr('data-val-required', 'Concept Email Opt-In Message is required');
  $("#PrivacyPolicy ").attr('data-val-required', 'Concept Privacy Policy is required');
 }
   $('form').removeData('validator');
    $('form').removeData('unobtrusiveValidation');
    $.validator.unobtrusive.parse('form');
}
Sign up to request clarification or add additional context in comments.

5 Comments

I added this and showConceptOptInMessage value is coming as undefined. What am I missing here? How to call this function or what to pass as container if I do something like this '<%=Html.CheckBoxFor(m => m.SnapfingerOptInDefaultToChecked, new { onclick="AddValidation()"} )%>` . Or is there any other way to call this function on check box click event?
I've edited the answer removed the container as you don't have the div that is the main div name, directly call the dom elements within the method, i.e. AddValidation() { $("#ShowConceptOptInMessage").val()}
I figured that out but issue is, once I check the field it is working but when I unchecked it, this validations should be removed which is not happening. I tried ` $( " #ConceptEmailOptInMessage").attr('data-val-required', 'Concept Email Opt-In Message is required', true);` & ` $( " #ConceptEmailOptInMessage").attr('data-val-required', 'Concept Email Opt-In Message is required', false);` which is not working
everytime you call addvalidation method, if the checkbox is checked, add the validation, if unchecked remove the attr i.e. $( " #ConceptEmailOptInMessage").removeAttr('data-val-required') something like that;and call this again $('form').removeData('validator'); $('form').removeData('unobtrusiveValidation'); $.validator.unobtrusive.parse('form');
Minor change, $( "#ShowConceptOptInMessage").val(); always gives me true whether its checked or unchecked so I used $('#ShowConceptOptInMessage').is(':checked') which gives me true...false based on checked...unchecked. Thank you

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.