If you need client-side validation in addition to validating the model on the server, I think the best way is to have a custom validation attribute (like suggested by Jaroslaw). I am including the source here of the one I am using.
User attribute:
public class RequiredIfAttribute : DependentPropertyAttribute { private readonly RequiredAttribute innerAttribute = new RequiredAttribute(); public object TargetValue { get; set; } public RequiredIfAttribute(string dependentProperty, object targetValue) : base(dependentProperty) { TargetValue = targetValue; } protected override ValidationResult IsValid(object value, ValidationContext validationContext) {
JQuery validation extension:
$.validator.unobtrusive.adapters.add('requiredif', ['dependentproperty', 'targetvalue'], function (options) { options.rules['requiredif'] = { dependentproperty: options.params['dependentproperty'], targetvalue: options.params['targetvalue'] }; options.messages['requiredif'] = options.message; }); $.validator.addMethod('requiredif', function (value, element, parameters) { var id = '#' + parameters['dependentproperty'];
Decorating a property with an attribute:
[Required] public bool IsEmailGiftCertificate { get; set; } [RequiredIf("IsEmailGiftCertificate", true, ErrorMessage = "Please provide Your Email.")] public string YourEmail { get; set; }
PeaceFrog
source share