验证基于其他领域?
作者:互联网
在ASP.NET MVC 2中,我有一个Linq to sql类,其中包含一系列字段.现在,当另一个字段具有特定(枚举)值时,则需要其中一个字段.
到目前为止,我编写了一个自定义验证属性,该属性可以将枚举作为属性,但是我不能说,例如:EnumValue = this.OtherField
我应该怎么做?
解决方法:
MVC2附带了一个示例“ PropertiesMustMatchAttribute”,该示例显示了如何使DataAnnotations为您工作,并且它在.NET 3.5和.NET 4.0中均应工作.该示例代码如下所示:
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = true)]
public sealed class PropertiesMustMatchAttribute : ValidationAttribute
{
private const string _defaultErrorMessage = "'{0}' and '{1}' do not match.";
private readonly object _typeId = new object();
public PropertiesMustMatchAttribute(string originalProperty, string confirmProperty)
: base(_defaultErrorMessage)
{
OriginalProperty = originalProperty;
ConfirmProperty = confirmProperty;
}
public string ConfirmProperty
{
get;
private set;
}
public string OriginalProperty
{
get;
private set;
}
public override object TypeId
{
get
{
return _typeId;
}
}
public override string FormatErrorMessage(string name)
{
return String.Format(CultureInfo.CurrentUICulture, ErrorMessageString,
OriginalProperty, ConfirmProperty);
}
public override bool IsValid(object value)
{
PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(value);
// ignore case for the following
object originalValue = properties.Find(OriginalProperty, true).GetValue(value);
object confirmValue = properties.Find(ConfirmProperty, true).GetValue(value);
return Object.Equals(originalValue, confirmValue);
}
}
当使用该属性时,而不是将其放在模型类的属性上,而是将其放在类本身上:
[PropertiesMustMatch("NewPassword", "ConfirmPassword", ErrorMessage = "The new password and confirmation password do not match.")]
public class ChangePasswordModel
{
public string NewPassword { get; set; }
public string ConfirmPassword { get; set; }
}
当在您的自定义属性上调用“ IsValid”时,会将整个模型实例传递给它,以便您可以通过这种方式获取从属属性值.您可以轻松地遵循此模式来创建甚至更一般的比较属性.
标签:asp-net-mvc-2,asp-net-mvc-2-validation,c 来源: https://codeday.me/bug/20191024/1917090.html