DataAnnotations “NotRequired” attribute

后端 未结 4 1327
天涯浪人
天涯浪人 2021-02-13 19:13

I\'ve a model kind of complicated.

I have my UserViewModel which has several properties and two of them are HomePhone and WorkPhone

4条回答
  •  名媛妹妹
    2021-02-13 19:39

    I wouldn't go with the modelBinder; I'd use a custom ValidationAttribute:

    public class UserViewModel
    {
        [Required]
        public string Name { get; set; }
    
        public HomePhoneViewModel HomePhone { get; set; }
    
        public WorkPhoneViewModel WorkPhone { get; set; }
    }
    
    public class HomePhoneViewModel : PhoneViewModel 
    {
    }
    
    public class WorkPhoneViewModel : PhoneViewModel 
    {
    }
    
    public class PhoneViewModel 
    {
        public string CountryCode { get; set; }
    
        public string AreaCode { get; set; }
    
        [CustomRequiredPhone]
        public string Number { get; set; }
    }
    

    And then:

    [AttributeUsage(AttributeTargets.Property]
    public class CustomRequiredPhone : ValidationAttribute
    {
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            ValidationResult validationResult = null;
    
            // Check if Model is WorkphoneViewModel, if so, activate validation
            if (validationContext.ObjectInstance.GetType() == typeof(WorkPhoneViewModel)
             && string.IsNullOrWhiteSpace((string)value) == true)
            {
                this.ErrorMessage = "Phone is required";
                validationResult = new ValidationResult(this.ErrorMessage);
            }
            else
            {
                validationResult = ValidationResult.Success;
            }
    
            return validationResult;
        }
    }
    

    If it is not clear, I'll provide an explanation but I think it's pretty self-explanatory.

提交回复
热议问题