Для этого вам необходимо создать собственный атрибут проверки. Ниже приведен код, который поможет вам это сделать.
public class RequiredIfAttribute : RequiredAttribute
{
private string PropertyName { get; set; }
private object DesiredValue { get; set; }
public RequiredIfAttribute(string propertyName, object desiredvalue)
{
PropertyName = propertyName;
DesiredValue = desiredvalue;
}
protected override ValidationResult IsValid(object value, ValidationContext context)
{
object instance = context.ObjectInstance;
Type type = instance.GetType();
Object proprtyvalue = type.GetProperty(PropertyName).GetValue(instance, null);
if (proprtyvalue.ToString() == DesiredValue.ToString())
{
ValidationResult result = base.IsValid(value, context);
return result;
}
return ValidationResult.Success;
}
}
Тогда вы должны украсить вашу собственность с этим атрибутом (читать комментарии в коде для понимания)
public class User
{
/// <summary>
/// Gets or Sets Usertype.
/// </summary>
public string UserType { get; set; }
/// <summary>
/// Gets or Sets KurumKodu.
/// Here "Usertype" is property. In that you have to assign current user's role.
/// "user" is constant role. If "UserType" has value as "user" then this will be required.
/// </summary>
[RequiredIf("UserType", "user", ErrorMessage = "It is required")]
public decimal KurumKodu { get; set; }
}
Если вы хотите добавить на стороне клиента проверки (ненавязчивый), то, пожалуйста, см. ниже ссылку.
RequiredIf Conditional Validation Attribute
Вы должны создать свой собственный атрибут проверки (и реализовать 'IClientValidatable' для проверки на стороне клиента) –
У вас есть образцы кода? – kodcu
@kodcu Пожалуйста, проверьте http://stackoverflow.com/questions/7390902/requiredif-conditional-validation-attribute – Kamo