Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional Validation in asp.net MVC4

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?

like image 917
SoftwareSavant Avatar asked Oct 11 '12 15:10

SoftwareSavant


2 Answers

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.

like image 121
Darin Dimitrov Avatar answered Nov 08 '22 01:11

Darin Dimitrov


Another solution suggested by Andy West on his blog is to Conditionally Remove Fields from the Model State in the Controller:

When the form is posted, remove the fields from the model state so they’re not validated:

if (Request.IsAuthenticated)
{
    ModelState.Remove("CommenterName");
    ModelState.Remove("Email");
}

That worked for me.

like image 45
Pierre Avatar answered Nov 08 '22 01:11

Pierre