我有以下类用于自定义验证:
[AttributeUsage(AttributeTargets.Property, AllowMultiple=false, Inherited=true)]
public sealed class RequiredIfAnyTrueAttribute : ValidationAttribute, IClientValidatable
{
private const string DefaultErrorMessage = "{0} is required";
public List<string> OtherProperties { get; private set; }
public RequiredIfAnyTrueAttribute(string otherProperties)
: base(DefaultErrorMessage)
{
if (string.IsNullOrEmpty(otherProperties))
throw new ArgumentNullException("otherProperty");
OtherProperties = new List<string>(otherProperties.Split(new char[] { '|', ',' }));
}
public override string FormatErrorMessage(string name)
{
return string.Format(ErrorMessageString, name);
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
if (value == null)
{
foreach (string s in OtherProperties)
{
var otherProperty = validationContext.ObjectType.GetProperty(s);
var otherPropertyValue = otherProperty.GetValue(validationContext.ObjectInstance, null);
if (otherPropertyValue.Equals(true))
return new ValidationResult(FormatErrorMessage(validationContext.DisplayName));
}
}
return ValidationResult.Success;
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
var clientValidationRule = new ModelClientValidationRule()
{
ErrorMessage = FormatErrorMessage(metadata.GetDisplayName()),
ValidationType = "requiredifanytrue"
};
clientValidationRule.ValidationParameters.Add("otherproperties", string.Join("|",OtherProperties));
return new[] { clientValidationRule };
}
}我的ViewModel是:
public class SampleViewModel
{
public bool PropABC { get; set; }
public bool PropXYZ { get; set; }
[RequiredIfAnyTrue("PropABC|PropXYZ")]
public int? TestField { get; set; }
}当我的强类型视图呈现时,一切都会正常工作。如果选择了PropABC或PropXYZ,则需要输入TestField的值。客户端和服务器端的验证都是功能性的。
然而,考虑到以下一系列事件:
为了解决#5,我通常会通过jquery将单击事件附加到复选框,以便重新启动验证。
是否有一种首选的/推荐的方法来手动强制客户端验证(给定MVC3 + unobstrusive + jquery? )?
发布于 2011-08-28 13:57:43
Shawn,附加事件是获得验证以重新启动的最佳方法。
我建议创建一个名为“called”的类(或类似于这些代码的类),将其添加到要验证的每个元素中,然后使用jQuery将其附加到每个元素的单击和模糊事件(可能还包括更改事件),并验证元素如下:
$("form").validate().element(this);发布于 2011-08-25 18:38:55
你需要写你自己的属性吗?如果没有,我认为你可以避免“重新发明轮子”。
FoolProof工作得很好。您可以将其作为一个NuGet包获得。
NuGet:安装包万无一失
它包括许多伟大的属性,为各种组合的飞行所需的字段等。
发布于 2013-11-06 13:45:44
FoolProof仍然处于测试版,不适用于嵌套的视图模型,也不适用于数组。
https://stackoverflow.com/questions/7195419
复制相似问题