开发者

ASP.Net MVC 3 ViewModel, unobtrusive JavaScript and custom validation

开发者 https://www.devze.com 2023-04-12 13:16 出处:网络
I\'m trying to write a custom validation method in my app - I have it working server side, but I\'m trying to extend that so that it also implements in the unobtrusive javascript client side validatio

I'm trying to write a custom validation method in my app - I have it working server side, but I'm trying to extend that so that it also implements in the unobtrusive javascript client side validation. I'm using a viewmodel as well, for added fun.

Here's what I have as a trivial test - it's pretty simple - a child object has three fields - the custom validation I'm writing is that at least one of the fields must be filled in (obviously my actual app has a significantly more complex model than this):

Model:

public class Child
{
    public int Id { get; set; }
    [MustHaveFavouriteValidator("FavouritePudding", "FavouriteGame")]
    public string FavouriteToy { get; set; }
    public string FavouritePudding { get; set; }
    public string FavouriteGame { get; set; }
}

ViewModel:

public class ChildViewModel
{
    public Child theChild { get; set; }
}

Controller:

    public ActionResult Create()
    {
        var childViewModel = new PeopleAgeGroups.ViewModels.ChildViewModel();
        return View(childViewModel);
    } 

I've followed what documentatation I can find online and whipped up a custom validator that looks like this:

public class MustHaveFavouriteValidator:ValidationAttribute, IClientValidatable
{
    private const string defaultError = "You must have one favourite";

    public string firstOtherFavourite { get; set; }
    public string secondOtherFavourite { get; set; }

    public MustHaveFavouriteValidator(string firstFave, string secondFave)
        : base(defaultError)
    {
        firstOtherFavourite = firstFave;
        secondOtherFavourite = secondFave;
    }

    public override string FormatErrorMessage(string name)
    {
        return string.Format(ErrorMessageString, name, firstOtherFavourite, secondOtherFavourite);
    }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {

        var aFavouriteObject = validationContext.ObjectInstance.GetType().GetProperty(firstOtherFavourite);
        var bFavouriteObject = validationContext.ObjectInstance.GetType().GetProperty(secondOtherFavourite);

        var aFavourite = aFavouriteObject.GetValue(validationContext.ObjectInstance, null);
        var bFavourite = bFavouriteObject.GetValue(validationContext.ObjectInstance, null);

        if(value==null && aFavourite ==null && bFavourite == null){
            return new ValidationResult(FormatErrorMessage(validationContext.DisplayName), new[] { validationContext.MemberName, aFavouriteObject.Name, bFavouriteObject.Name });


        }


        return ValidationResult.Success;
    }

    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
    {
        return new[] { new MustHaveFavourite(FormatErrorMessage(metadata.GetDisplayName()), firstOtherFavourite, secondOtherFavourite) };
    }
}

Good stuff, my server side validation works. Next I have the model client validation rule:

public class MustHaveFavourite : ModelClientValidationRule
{
    public MustHaveFavourite(string errorMessage, string firstotherfavourite, string secondotherfavourite)
    {
        ErrorMessage = errorMessage;
        ValidationType = "musthavefavourite";
        ValidationParameters.Add("firstotherfavourite", firstotherfavourite);
        ValidationParameters.Add("secondotherfavourite", secondotherfavourite);
    }
}

and finally, my custom javascript to tie it all together:

(function ($) {
jQuery.validator.addMethod("musthavefavourite", function (value, element, params) {

    var $firstOtherFavouriteObject = $('#' + 开发者_如何转开发params.firstotherfavourite);
    var firstOtherFavourite = $firstOtherFavouriteObject.val();
    var $secondOtherFavouriteObject = $('#' + params.secondotherfavourite);
    var secondOtherFavourite = $secondOtherFavouriteObject.val();
    if (value == '' && firstOtherFavourite == '' && secondOtherFavourite == '') {
        return false;
    } else {
        return true;

    }
});
$.validator.unobtrusive.adapters.add("musthavefavourite", ["firstotherfavourite", "secondotherfavourite"],
    function (options) {
        options.rules['musthavefavourite'] = {
            firstotherfavourite: options.params.firstotherfavourite,
            secondotherfavourite: options.params.secondotherfavourite
        };
        options.messages['musthavefavourite'] = options.mesage;
    }

);
} (jQuery));

The problem that occurs is that the in the generated HTML, I get my text elements that have an id that are prefixed "theChild_" - this makes sense since my viewmodel declares a Child object, however, my custom function doesn't have the prefix on the element names. Is there any way to pass that prefix through to the javascript without actually hacking it up to look like this:

jQuery.validator.addMethod("musthavefavourite", function (value, element, params) {
    var $firstOtherFavouriteObject = $('#theChild_' + params.firstotherfavourite);
    var firstOtherFavourite = $firstOtherFavouriteObject.val(); 

which to my mind kind of defeats the idea of creating my validation serverside and then hooking all this extra gumf up to go through the unobtrusive validation since I've created a piece of javascript that can only really be used with that combination of form/viewmodel combination.


You can modify your validator to check for any prefix, and add the prefix to the selector for the elements to be checked, as I outline in my answer to this question: MVC3 custom validation: compare two dates. You will need to either (1) change the selectors to search by name, instead of by id, or (2) split the id by using _ instead of ..

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号