mva*_*lla 2 entity-framework data-annotations
有没有办法做这个问题正在做的事情(或者或需要验证),但不是将它应用于整个类,我只想在类中的两个特定字段上应用验证。
例如
public class FooModel {
[Required]
public string Name { get; set; }
[Required]
public decimal Cost { get; set; }
public int Bar1 { get; set; }
public float Bar2 { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
我只想将 Bar1 和 Bar2 限制为非此即彼的要求。它们不能都为空。有没有办法做到这一点?
您可以通过实现来添加服务器端验证 IValidatableObject
public class FooModel: IValidatableObject
{
[Required]
public string Name { get; set; }
[Required]
public decimal Cost { get; set; }
public int Bar1 { get; set; }
public float Bar2 { get; set; }
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
if (Bar1 == null && Bar2 == null)
yield return new ValidationResult("Either Bar1 or Bar2 must be specified");
}
}
Run Code Online (Sandbox Code Playgroud)
参考:
使用 IValidatableObject 和 POCO 进行更复杂的验证
| 归档时间: |
|
| 查看次数: |
1138 次 |
| 最近记录: |