Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
948 views
in Technique[技术] by (71.8m points)

jquery validate - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...