bee*_*bul 3 validation attributes viewmodel asp.net-mvc-2
有人可以帮我解决这个问题.我正在试图弄清楚如何在表单上检查两个值,必须填写两个项目中的一个.如何检查以确保输入了一个或两个项目?
我在ASP.NET MVC 2中使用viewmodels.
这里有一小段代码:
风景:
Email: <%=Html.TextBoxFor(x => x.Email)%>
Telephone: <%=Html.TextBoxFor(x => x.TelephoneNumber)%>
Run Code Online (Sandbox Code Playgroud)
视图模型:
[Email(ErrorMessage = "Please Enter a Valid Email Address")]
public string Email { get; set; }
[DisplayName("Telephone Number")]
public string TelephoneNumber { get; set; }
Run Code Online (Sandbox Code Playgroud)
我想要提供这些细节中的任何一个.
谢谢你的任何指示.
您可以使用与作为PropertiesMustMatchFile-> New-> ASP.NET MVC 2 Web应用程序一部分的属性大致相同的方式执行此操作.
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = true)]
public sealed class EitherOrAttribute : ValidationAttribute
{
private const string _defaultErrorMessage = "Either '{0}' or '{1}' must have a value.";
private readonly object _typeId = new object();
public EitherOrAttribute(string primaryProperty, string secondaryProperty)
: base(_defaultErrorMessage)
{
PrimaryProperty = primaryProperty;
SecondaryProperty = secondaryProperty;
}
public string PrimaryProperty { get; private set; }
public string SecondaryProperty { get; private set; }
public override object TypeId
{
get
{
return _typeId;
}
}
public override string FormatErrorMessage(string name)
{
return String.Format(CultureInfo.CurrentUICulture, ErrorMessageString,
PrimaryProperty, SecondaryProperty);
}
public override bool IsValid(object value)
{
PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(value);
object primaryValue = properties.Find(PrimaryProperty, true /* ignoreCase */).GetValue(value);
object secondaryValue = properties.Find(SecondaryProperty, true /* ignoreCase */).GetValue(value);
return primaryValue != null || secondaryValue != null;
}
}
Run Code Online (Sandbox Code Playgroud)
此函数的关键部分是IsValid函数,该函数确定两个参数中的一个是否具有值.
与普通的基于属性的属性不同,这适用于类级别,可以像这样使用:
[EitherOr("Email", "TelephoneNumber")]
public class ExampleViewModel
{
[Email(ErrorMessage = "Please Enter a Valid Email Address")]
public string Email { get; set; }
[DisplayName("Telephone Number")]
public string TelephoneNumber { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
您应该能够根据需要为每个表单添加多个,但如果您想强制他们在两个以上的框中输入一个值(例如电子邮件,电话或传真),那么您可能是最好的将输入更改为更多值的数组并以这种方式解析它.