MVC Form Validation on Multiple Fields

前端 未结 3 1078
夕颜
夕颜 2020-12-01 09:20

How would I go about having multiple textboxes on an MVC 3 form treated as one for the purposes of validation?

It\'s a simple phone number field with one textbox for

3条回答
  •  隐瞒了意图╮
    2020-12-01 10:22

    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 GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
            {
                yield return new ModelClientValidationRule
                {
                    ErrorMessage = this.ErrorMessage,
                    ValidationType = "multifield"
                };
            }
        }
    

提交回复
热议问题