MVC表单验证多个字段

MVC表单验证多个字段

本文介绍了MVC表单验证多个字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我怎么会去为一个进行验证的目的,治疗的MVC 3表单上有多个文本框?

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

这是一个文本框区域为code,一个为preFIX,一个是最后四位数字的简单电话号码字段。

It's a simple phone number field with one textbox for area code, one for prefix and one for the last four digits.

实际上有两个验证要求:

There are really two validation requirements:

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

1) They're all required.2) They must all contain integers.

现在这样做是为了单个字段时,这很简单,但我怎么能创建一个ASP.NET的CustomValidator与MVC等同,这样我就可以验证这三个领域作为一个整体?

Now this is simple when doing it for individual fields but how can I create the equivalent of an ASP.NET CustomValidator with MVC so that I can validate all three fields as a whole?

推荐答案

其实我最终实现自定义的 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"
            };
        }
    }

这篇关于MVC表单验证多个字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-12 10:17