Conditional Validation in asp.net MVC4

asp.net-mvc-4, jquery-validate

Solution

ASP.NET MVC 3 uses jquery unobtrusive validation to perform client side validation. So you could either write a custom `RequiredIf` validation attribute or use the one provided in Mvc Foolproof Validation and then:

public class MyViewModel
{
    [RequiredIf("IsFlagSet", true)]
    [Remote("ValidateHosFin", "EditEncounter")]
    [MinLength(6)]
    public string HospitalFinNumber { get; set; }

    public bool IsFlagSet { get; set; }

    public string EncFlag { get; set; }
}

Then all that's left is to include the `jquery.validate.js` and `jquery.validate.unobtrusive.js` scripts or use the corresponding bundle in ASP.NET MVC 4 that includes them.

Problem

I want to be able to kick off some validation functions based upon what controller a view is called from... I will set a variable in ViewState or something and that will help me to know what controller this view was called from. In other words, I want the validation to be required if a certain variable is set... Here is how I use to do in MVC2 when I just put Jquery into my code... ``` HospitalFinNumber: { required: function (element) { debugger; return '@isFlagSet' != 'True'; }, minlength: 6, remote: function () { //debugger; return { url: '@Url.Action("ValidateHosFin", "EditEncounter")', data: { hospitalFin: $('#HospitalFinNumber').val(), encflag: '@encflag' } }; } } ``` You see what I am doing there. This validation would only be required if a certain variable is set... In this case, the variable isFlagSet... I would then set min Length and call a remote function to ensure that the value is unique. I don't want to do this in all cases. From all I have read so far, there is no clear way to accomplish this using unobrtusive ajax? Am I wrong, is there a way you can do this? If not, how can I just place regular old jquery validation into my code?

Original source

Related problems