Ok, so I found a way to get the result that I wanted, although it was a little more work than I wanted / assumed it would be. I was missing that I did not inject IClientValidatable into my custom validation class and had to add my special verification to the jQuery Validator add-on that I tried, but not with IClientValidatable implanted into the custom validation class, I’ll quickly get down to how to get this job, assuming you have all the jQuery-created stuff / included
First create a simple model that uses a special validation attribute
public class Person { [Required] [Display( Name="Name")] public string Name { get; set; } public int Age { get; set; }
A custom validation class that uses reflection to retrieve the property of the name of a validated row with
Note from 08/15/2012: if you are using MVC 4, you need to reference System.web.mvc 3.0 to use IClientValidatable, since ModelClientValidationRule does not seem to exist in MVC 4
public class OneOfTwoRequired : ValidationAttribute, IClientValidatable { private const string defaultErrorMessage = "{0} or {1} is required."; private string otherProperty; public OneOfTwoRequired(string otherProperty) : base(defaultErrorMessage) { if (string.IsNullOrEmpty(otherProperty)) { throw new ArgumentNullException("otherProperty"); } this.otherProperty = otherProperty; } public override string FormatErrorMessage(string name) { return string.Format(ErrorMessageString, name, otherProperty); } protected override ValidationResult IsValid(object value, ValidationContext validationContext) { PropertyInfo otherPropertyInfo = validationContext.ObjectInstance.GetType().GetProperty(otherProperty); if (otherPropertyInfo == null) { return new ValidationResult(string.Format("Property '{0}' is undefined.", otherProperty)); } var otherPropertyValue = otherPropertyInfo.GetValue(validationContext.ObjectInstance, null); if (otherPropertyValue == null && value == null) { return new ValidationResult(this.FormatErrorMessage(validationContext.DisplayName)); } return ValidationResult.Success; } public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context) { yield return new ModelClientValidationRule { ErrorMessage = FormatErrorMessage(metadata.DisplayName),
Add this to the view or partial view, you have to make sure that this is not the $ (document) .ready method
jQuery.validator.addMethod("oneoftworequired", function (value, element, param) { if ($('#Phone).val() == '' && $('
jQuery authentication stuff seems to be necessary if you want to validate the form without posting back or on the page loading, and for that you just call $ ('form'). valid ()
Hope this helps someone :)