c# - 多个字段的 MVC 表单验证

标签 c# asp.net-mvc validation forms asp.net-mvc-3

为了验证目的,我将如何将 MVC 3 表单上的多个文本框视为一个文本框?

这是一个简单的电话号码字段,其中一个文本框用于区号,一个用于前缀,一个用于最后四位数字。

实际上有两个验证要求:

1) 它们都是必需的。 2) 它们必须都包含整数。

现在对单个字段执行此操作很简单,但我如何使用 MVC 创建 ASP.NET CustomValidator 的等效项,以便我可以整体验证所有三个字段?

最佳答案

实际上,我最终实现了自定义 ValidationAttribute 来解决这个问题,使用 CompareAttribute 中提供的相同类型的逻辑,允许您使用反射来评估其他值特性。这使我能够在属性级别而不是模型级别实现它,并且还允许通过不显眼的 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"
            };
        }
    }

关于c# - 多个字段的 MVC 表单验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6075339/

相关文章:

c# - ASP.NET 中的 session 变量返回 ModalBox 中的先前值?

java - 使用扫描仪验证多个输入

angularjs - angularjs 中 !$pristine 与 $dirty 之间的区别是什么

c# 内存不足异常与 System.Drawing.Image

c# - System.Diagnostics.Stopwatch 在 Elapsed... 属性中返回负数

c# - 存储在 CallContext 中的数据会在请求之间泄漏吗?

ASP.NET MVC 5 - RazorGenerator 与发布期间的发布预编译

javascript - 模态视图重新加载内容(Bootstrap MVC ASP.NET)

tensorflow - Keras:训练数据的自定义数据验证回调总是返回验证数据结果

c# - 如何在派生类时更改常量或静态变量的值?