如何在MVC中使用必需属性和验证

时间:2013-12-30 09:18:41

标签: asp.net-mvc

我有一个名为Passenger Name的字段,这是一个必填字段(需要显示*)。选中复选框时会显示此字段。如果乘客是空的,我需要验证该字段。我们在项目中使用MVC。

我尝试使用以下代码:

[Required(ErrorMessage = "Passenger Name mandatory if specifying Enhanced Data")]
public string PassengerName { get; set; }

即使没有勾选复选框,也会被解雇。我只有在选中复选框时才需要验证..

请帮忙!

1 个答案:

答案 0 :(得分:0)

您必须为此使用自定义验证属性。

以下是示例代码

public class RequiredIfAttribute:RequiredAttribute         {             private String PropertyName {get;组; }             private Object DesiredValue {get;组; }

        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;
        }
    }

此处PropertyName是您要在其上创建条件的属性DesiredValue是PropertyName(property)的特定值,您的其他属性必须根据需要进行验证

说你有以下

public enum UserType
{
 Admin,
 Regular
}

public class User
{
   public UserType UserType{get;set;}
   [RequiredIf("UserType",UserType.Admin,ErrorMessageResourceName="PasswordRequired", ErrorMessageResourceType = typeof(ResourceString))
   public string Password
   {
   get;
   set;
   }
}

最后但并非最不重要的是,为您的属性注册适配器,以便它可以进行客户端验证(我把它放在global.asax,Application_Start中)

DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(RequiredIfAttribute),typeof(RequiredAttributeAdapter));
相关问题