Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6675231
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 26, 20262026-05-26T03:49:43+00:00 2026-05-26T03:49:43+00:00

I’m trying to write a custom validation method in my app – I have

  • 0

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.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-26T03:49:44+00:00Added an answer on May 26, 2026 at 3:49 am

    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
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a French site that I want to parse, but am running into
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
I'm trying to create an if statement in PHP that prevents a single post
I am trying to loop through a bunch of documents I have to put
I'm working with an upstream system that sometimes sends me text destined for HTML/XML
I am trying to understand how to use SyndicationItem to display feed which is
Basically, what I'm trying to create is a page of div tags, each has
link Im having trouble converting the html entites into html characters, (&# 8217;) i
That's pretty much it. I'm using Nokogiri to scrape a web page what has
I have just tried to save a simple *.rtf file with some websites and

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.