简体   繁体   中英

Data Annotation Validation for a Group of Fields in Model

I am new to MVC 3 Data Annotations and I just want to ask that if its possible to add Validation on a Group of Fields in Model and Display the validation if none of it has Value?

this is the set of fields in my Data model

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

    }

And I want to add validation if one from Phone,Mobile or Email doesn't have value

Thanks

You can implement IValidatableObject interface and add validation for all necessary properties:

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

Of course you should remove [Required] attributes then from those properties.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM