Example #1
0
        private static IDictionary <string, object> GetUnobtrusiveValidationAttributes(PropertyInfo propertyInfo, ModelMetadata modelMetadata, IModelMetadataProvider provider)
        {
            var hasRequiredAttribute = false;
            var propType             = GetPropertyType(propertyInfo);
            var attrs = new AttributeDictionary();

            var valAttrs = propertyInfo.GetCustomAttributes(typeof(ValidationAttribute));

            ValidationAttributeAdapterProvider adapterProvider = new ValidationAttributeAdapterProvider();
            IAttributeAdapter adapter;

            var context = new ClientModelValidationContext(
                new ActionContext(),
                modelMetadata,
                provider,
                attrs);

            foreach (ValidationAttribute valAttr in valAttrs)
            {
                if (valAttr is RequiredAttribute)
                {
                    hasRequiredAttribute = true;
                }

                adapter = adapterProvider.GetAttributeAdapter(valAttr, null);
                adapter.AddValidation(context);
            }

            if (!hasRequiredAttribute && context.ModelMetadata.IsRequired)
            {
                adapter = adapterProvider.GetAttributeAdapter(new RequiredAttribute(), null);
                adapter.AddValidation(context);
            }

            if (propType == typeof(float) ||
                propType == typeof(double) ||
                propType == typeof(decimal))
            {
                MergeAttribute(context.Attributes, "data-val", "true");
                MergeAttribute(context.Attributes, "data-val-number", GetErrorMessage(context.ModelMetadata));
            }

            return(attrs.ToDictionary(p => p.Key, pp => (object)pp.Value));
        }