You have to create custom validation attribute for this. Below code may help you to do this.
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;
}
}
Then you have to decorate your property with this attribute
(read the comments in code for understanding)
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; }
}
If you want to add Client Side validation(unobtrusive) then, please see below link.
RequiredIf Conditional Validation Attribute