您可以编写自定义条件验证属性:
public class RequiredIfPermissionIdsAttribute : RequiredAttribute
{
public int[] PermissionIds { get; private set; }
public RequiredIfPermissionIdsAttribute(params int[] permissionIds)
{
PermissionIds = permissionIds ?? new int[0];
}
public override bool IsValid(object value)
{
int permissionId = Helpers.ConvertToInt(Services.UserService.GetCurrentPermissionId().ToString());
if (PermissionIds.Contains(permissionId))
{
return base.IsValid(value);
}
// the current permission id is not in the list of permission ids
// that require validation => we consider the model valid
return true;
}
}
然后你可以用这个属性装饰你的财产:
[RequiredIfPermissionIds(0, 1)]
public string SomeProperty { get; set; }
或者,您可以使用白名单方法,而不是使用黑名单方法:
public class NotRequiredIfPermissionIdsAttribute : RequiredAttribute
{
public NotRequiredIfPermissionIdsAttribute(params int[] permissionIds)
{
PermissionIds = permissionIds ?? new int[0];
}
public int[] PermissionIds { get; private set; }
public override bool IsValid(object value)
{
int permissionId = Helpers.ConvertToInt(Services.UserService.GetCurrentPermissionId().ToString());
if (!PermissionIds.Contains(permissionId))
{
return base.IsValid(value);
}
return true;
}
}
进而:
[NotRequiredIfPermissionIds(2)]
public string SomeProperty { get; set; }