西蒙因斯的博客文章似乎已经过时。
无需使用DataAnnotationsModelValidator或执行DataAnnotationsModelValidator注册。
您可以使用下面的代码:
[AttributeUsage(AttributeTargets.Property, AllowMultiple=false)]
public class RequiredIfAttribute : ValidationAttribute, IClientValidatable {
private const string _defaultErrorMessage = "'{0}' is required when {1} equals {2}.";
public string DependentProperty { get; set; }
public object TargetValue { get; set; }
public RequiredIfAttribute(string dependentProperty, object targetValue):base(_defaultErrorMessage) {
this.DependentProperty = dependentProperty;
this.TargetValue = targetValue;
}
public override string FormatErrorMessage(string name) {
return String.Format(CultureInfo.CurrentCulture, ErrorMessageString, name, DependentProperty, TargetValue);
}
protected override ValidationResult IsValid(object value, ValidationContext context) {
if (context.ObjectInstance != null) {
Type type = context.ObjectInstance.GetType();
PropertyInfo info = type.GetProperty(DependentProperty);
object dependentValue;
if (info != null) {
dependentValue = info.GetValue(context.ObjectInstance, null);
if (object.Equals(dependentValue, TargetValue)) {
if (string.IsNullOrWhiteSpace(Convert.ToString(value))) {
return new ValidationResult(ErrorMessage);
}
}
}
}
return ValidationResult.Success;
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context) {
ModelClientValidationRule rule = new ModelClientValidationRule();
rule.ErrorMessage = this.FormatErrorMessage(metadata.PropertyName);
rule.ValidationType = "requiredif";
rule.ValidationParameters.Add("depedentproperty", DependentProperty);
rule.ValidationParameters.Add("targetvalue", TargetValue);
yield return rule;
}
}
和JavaScript的一面:如果你正在使用jQuery:
$.validator.unobtrusive.adapters.add('requiredif', ['depedentproperty', 'targetvalue'], function (options) {
options.rules["required"] = function (element) {
return $('#' + options.params.depedentproperty).val() == options.params.targetvalue
};
if (options.message) {
options.messages["required"] = options.message;
}
$('#' + options.params.depedentproperty).blur(function() {
$('#' + options.element.name).valid();
});
});
thnx !!但问题是,在这种情况下,客户端验证不会工作? – bhuvin 2011-03-23 07:25:09
@bhuvin,不,它不会工作,但你可以通过实现IClientValidatable来实现它:http://devtrends.co.uk/blog/the-complete-guide-to-validation-in-asp .net-mvc-3-part-2 – 2011-03-23 07:28:32
@darin已经尝试过与其他东西,但它仍然没有工作 – bhuvin 2011-03-23 07:29:47