模型中一组字段的数据注释验证

时间:2015-07-14 08:32:20

标签: c# asp.net-mvc-3 validation data-annotations

我是MVC 3数据注释的新手,我只是想问一下,如果可以在模型中的一组字段上添加验证并显示验证,如果它没有任何值?

这是我的数据模型中的字段集

 public class ContactModel
    {
        public Nullable<int> Id { get; set; }


        [Display(Name = "Contact Firstname")]
        [Required(ErrorMessage = "Required!")]
        public string ContactFirstname { get; set; }

        [Display(Name = "Contact Lastname")]
        [Required(ErrorMessage = "Required!")]
        public string ContactLastname { get; set; }

        [Display(Name = "Contact Middlename")]
        public string ContactMiddlename { get; set; }

            [Display(Name = "Phone")]
            [Required(ErrorMessage = "Required!")]
            public string ContactPhone { get; set; }

            [Display(Name = "Mobile ")]
            [Required(ErrorMessage = "Required!")]
            public string ContactMobile { get; set; }

            [Display(Name = "Email")]
            [Required(ErrorMessage = "Required!")]
            public string ContactEmail { get; set; }

        [Display(Name = "Job Title")]
        [StringLength(50, ErrorMessage = "Max character reached!")]
        public string ContactJobTitle { get; set; }

    }

我想添加验证,如果来自电话,手机或电子邮件的人没有价值

由于

1 个答案:

答案 0 :(得分:1)

您可以实施IValidatableObject界面并为所有必要属性添加验证:

public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
    if(string.IsNullOrEmpty(Phone) || string.IsNullOrEmpty(Mobile) || string.IsNullOrEmpty(Email))
    {
         yield return new ValidationResult("Some error message");
    } 
}

当然,您应该从这些属性中删除[Required]属性。