假设我有一个带有FirstName和LastName的Person类.我希望用户必须在UI中输入两个值中的至少一个,但他可能不必输入每个值.
如果我在每个上面放置必需的属性/数据注释,那么这两者都是必需的.
如何为此规则进行服务器端验证(也使用客户端验证)?
解决方法
您可以为此使用自定义属性.简而言之,自定义属性将检索这两个值,然后确保至少有一个值具有值.有关更多信息,请参见
this page.这是一个例子(未经测试的代码):
[AttributeUsage(AttributeTargets.Property,AllowMultiple =false,Inherited = false)] public class ValidatePersonName: ValidationAttribute { protected override ValidationResult IsValid(object value,ValidationContext validationContext) { string FirstName = (string)validationContext.ObjectType.GetProperty("FirstName").GetValue(validationContext.ObjectInstance,null); string LastName = (string)validationContext.ObjectType.GetProperty("LastName").GetValue(validationContext.ObjectInstance,null); //check at least one has a value if (string.IsNullOrEmpty(FirstName) && string.IsNullOrEmpty(LastName)) return new ValidationResult("At least one is required!!"); return ValidationResult.Success; } }
用法:
class Person{ [ValidatePersonName] FirstName{get;set;} LastName{get;set;} }