且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

MVC表单验证多个字段

更新时间:2023-11-09 20:45:22

其实我最终实现自定义的 ValidationAttribute 来解决这个问题,使用相同类型的逻辑$ P的在 CompareAttribute ,允许您使用反射来评价其他属性的值$ psented。这让我在产权层面,而不是模型级别实现这个也允许客户端验证通过非侵入式JavaScript:

I actually ended up implementing a custom ValidationAttribute to solve this, using the same type of logic presented in CompareAttribute that allows you to use reflection to evaluate the values of other properties. This allowed me to implement this at the property level instead of the model level and also allows for client side validation via unobtrusive javascript:

public class MultiFieldRequiredAttribute : ValidationAttribute, IClientValidatable
    {
        private readonly string[] _fields;

        public MultiFieldRequiredAttribute(string[] fields)
        {
            _fields = fields;
        }

        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            foreach (string field in _fields)
            {
                PropertyInfo property = validationContext.ObjectType.GetProperty(field);
                if (property == null)
                    return new ValidationResult(string.Format("Property '{0}' is undefined.", field));

                var fieldValue = property.GetValue(validationContext.ObjectInstance, null);

                if (fieldValue == null || String.IsNullOrEmpty(fieldValue.ToString()))
                    return new ValidationResult(this.FormatErrorMessage(validationContext.DisplayName));
            }

            return null;
        }

        public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
            yield return new ModelClientValidationRule
            {
                ErrorMessage = this.ErrorMessage,
                ValidationType = "multifield"
            };
        }
    }