力驗證我已經使用了自定義的驗證下列類:MVC3自定義不引人注目的驗證 - 從複選框
[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 };
}
}
我的視圖模型爲:
public class SampleViewModel
{
public bool PropABC { get; set; }
public bool PropXYZ { get; set; }
[RequiredIfAnyTrue("PropABC|PropXYZ")]
public int? TestField { get; set; }
}
當我的強類型的視圖渲染,一切都看向工作正常。如果選擇了PropABC或PropXYZ,那麼我需要爲TestField輸入一個值。客戶端和服務器端驗證都是有效的。
然而,鑑於事件的順序如下:
- 檢查PropABC
- 提交表單
- 客戶端驗證火災的TestField需要
- 取消選中PropABC
- 客戶端驗證不重-firefire和驗證消息 將一直保留,直到表單提交
爲了解決#5,我通常會通過jquery onready將點擊事件附加到複選框以重新驗證。
是否有一個首選/推薦的方式來手動強制客戶端驗證給予MVC3 + unobstrusive + jQuery的?
你可以發佈自定義客戶端驗證,以及? –