Reviving CompareAttributeAdapter and ModelClientValidationEqualToRule

This commit is contained in:
Pranav K 2014-04-22 18:08:00 -07:00
parent cc00d8cff7
commit 3671e8c5b4
9 changed files with 383 additions and 2 deletions

View File

@ -71,6 +71,7 @@
<Compile Include="RequestContext.cs" />
<Compile Include="Validation\AssociatedValidatorProvider.cs" />
<Compile Include="Validation\ClientModelValidationContext.cs" />
<Compile Include="Validation\CompareAttributeAdapter.cs" />
<Compile Include="Validation\CompositeModelValidator.cs" />
<Compile Include="Validation\DataAnnotationsModelValidator.cs" />
<Compile Include="Validation\DataAnnotationsModelValidatorOfTAttribute.cs" />
@ -83,6 +84,7 @@
<Compile Include="Validation\IModelValidator.cs" />
<Compile Include="Validation\IModelValidatorProvider.cs" />
<Compile Include="Validation\InvalidModelValidatorProvider.cs" />
<Compile Include="Validation\ModelClientValidationEqualToRule.cs" />
<Compile Include="Validation\ModelClientValidationRegexRule.cs" />
<Compile Include="Validation\ModelClientValidationRule.cs" />
<Compile Include="Validation\ModelValidatedEventArgs.cs" />

View File

@ -4,11 +4,15 @@ namespace Microsoft.AspNet.Mvc.ModelBinding
{
public class ClientModelValidationContext
{
public ClientModelValidationContext([NotNull] ModelMetadata metadata)
public ClientModelValidationContext([NotNull] ModelMetadata metadata,
[NotNull] IModelMetadataProvider metadataProvider)
{
ModelMetadata = metadata;
MetadataProvider = metadataProvider;
}
public ModelMetadata ModelMetadata { get; private set; }
public IModelMetadataProvider MetadataProvider { get; private set; }
}
}

View File

@ -0,0 +1,79 @@
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
namespace Microsoft.AspNet.Mvc.ModelBinding
{
public class CompareAttributeAdapter : DataAnnotationsModelValidator<CompareAttribute>
{
public CompareAttributeAdapter([NotNull] CompareAttribute attribute)
: base(new CompareAttributeWrapper(attribute))
{
}
public override IEnumerable<ModelClientValidationRule> GetClientValidationRules(
[NotNull] ClientModelValidationContext context)
{
var errorMessage = ((CompareAttributeWrapper)Attribute).FormatErrorMessage(context);
var clientRule = new ModelClientValidationEqualToRule(errorMessage,
FormatPropertyForClientValidation(Attribute.OtherProperty));
return new [] { clientRule };
}
private static string FormatPropertyForClientValidation(string property)
{
return "*." + property;
}
private sealed class CompareAttributeWrapper : CompareAttribute
{
public CompareAttributeWrapper(CompareAttribute attribute)
: base(attribute.OtherProperty)
{
// Copy settable properties from wrapped attribute. Don't reset default message accessor (set as
// CompareAttribute constructor calls ValidationAttribute constructor) when all properties are null to
// preserve default error message. Reset the message accessor when just ErrorMessageResourceType is
// non-null to ensure correct InvalidOperationException.
if (!string.IsNullOrEmpty(attribute.ErrorMessage) ||
!string.IsNullOrEmpty(attribute.ErrorMessageResourceName) ||
attribute.ErrorMessageResourceType != null)
{
ErrorMessage = attribute.ErrorMessage;
ErrorMessageResourceName = attribute.ErrorMessageResourceName;
ErrorMessageResourceType = attribute.ErrorMessageResourceType;
}
}
public string FormatErrorMessage(ClientModelValidationContext context)
{
var displayName = context.ModelMetadata.GetDisplayName();
return string.Format(CultureInfo.CurrentCulture,
ErrorMessageString,
displayName,
GetOtherPropertyDisplayName(context));
}
private string GetOtherPropertyDisplayName(ClientModelValidationContext context)
{
// The System.ComponentModel.DataAnnotations.CompareAttribute doesn't populate the OtherPropertyDisplayName
// until after IsValid() is called. Therefore, by the time we get the error message for client validation,
// the display name is not populated and won't be used.
var metadata = context.ModelMetadata;
var otherPropertyDisplayName = OtherPropertyDisplayName;
if (otherPropertyDisplayName == null && metadata.ContainerType != null)
{
var otherProperty = context.MetadataProvider
.GetMetadataForProperty(() => metadata.Model,
metadata.ContainerType,
OtherProperty);
if (otherProperty != null)
{
return otherProperty.GetDisplayName();
}
}
return OtherProperty;
}
}
}
}

View File

@ -0,0 +1,18 @@
namespace Microsoft.AspNet.Mvc.ModelBinding
{
/// <summary>
/// Represents client side validation rule that determines if two values are equal.
/// </summary>
public class ModelClientValidationEqualToRule : ModelClientValidationRule
{
private const string EqualToValidationType = "equalto";
private const string EqualToValidationParameter = "other";
public ModelClientValidationEqualToRule([NotNull] string errorMessage,
[NotNull] object other)
: base(EqualToValidationType, errorMessage)
{
ValidationParameters[EqualToValidationParameter] = other;
}
}
}

View File

@ -63,7 +63,7 @@ namespace Microsoft.AspNet.Mvc.Razor.Host
var value = _resourceManager.GetString(name);
System.Diagnostics.Debug.Assert(value != null);
if (formatterNames != null)
{
for (var i = 0; i < formatterNames.Length; i++)

View File

@ -19,6 +19,7 @@
</PropertyGroup>
<ItemGroup>
<Content Include="Project.json" />
<Content Include="Resources.resx" />
</ItemGroup>
<ItemGroup>
<Compile Include="Binders\ArrayModelBinderTest.cs" />
@ -36,8 +37,10 @@
<Compile Include="Metadata\AssociatedMetadataProviderTest.cs" />
<Compile Include="Metadata\ModelMetadataTest.cs" />
<Compile Include="ModelBindingContextTest.cs" />
<Compile Include="Properties\Resources.Designer.cs" />
<Compile Include="Utils\SimpleHttpValueProvider.cs" />
<Compile Include="Validation\AssociatedValidatorProviderTest.cs" />
<Compile Include="Validation\CompareAttributeTest.cs" />
<Compile Include="Validation\DataAnnotationsModelValidatorProviderTest.cs" />
<Compile Include="Validation\DataAnnotationsModelValidatorTest.cs" />
<Compile Include="Validation\DataMemberModelValidatorProviderTest.cs" />

View File

@ -0,0 +1,46 @@
// <auto-generated />
namespace Microsoft.AspNet.Mvc.ModelBinding.Test
{
using System.Globalization;
using System.Reflection;
using System.Resources;
internal static class Resources
{
private static readonly ResourceManager _resourceManager
= new ResourceManager("Microsoft.AspNet.Mvc.ModelBinding.Test.Resources", typeof(Resources).GetTypeInfo().Assembly);
/// <summary>
/// Comparing {0} to {1}.
/// </summary>
internal static string CompareAttributeTestResource
{
get { return GetString("CompareAttributeTestResource"); }
}
/// <summary>
/// Comparing {0} to {1}.
/// </summary>
internal static string FormatCompareAttributeTestResource(object p0, object p1)
{
return string.Format(CultureInfo.CurrentCulture, GetString("CompareAttributeTestResource"), p0, p1);
}
private static string GetString(string name, params string[] formatterNames)
{
var value = _resourceManager.GetString(name);
System.Diagnostics.Debug.Assert(value != null);
if (formatterNames != null)
{
for (var i = 0; i < formatterNames.Length; i++)
{
value = value.Replace("{" + formatterNames[i] + "}", "{" + i + "}");
}
}
return value;
}
}
}

View File

@ -0,0 +1,123 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<data name="CompareAttributeTestResource" xml:space="preserve">
<value>Comparing {0} to {1}.</value>
</data>
</root>

View File

@ -0,0 +1,106 @@
using System.ComponentModel.DataAnnotations;
using Microsoft.AspNet.Testing;
using Xunit;
namespace Microsoft.AspNet.Mvc.ModelBinding
{
public class CompareAttributeAdapterTest
{
[Fact]
[ReplaceCulture]
public void ClientRulesWithCompareAttribute_ErrorMessageUsesDisplayName()
{
// Arrange
var metadataProvider = new DataAnnotationsModelMetadataProvider();
var metadata = metadataProvider.GetMetadataForProperty(() => null, typeof(PropertyDisplayNameModel), "MyProperty");
var attribute = new CompareAttribute("OtherProperty");
var context = new ClientModelValidationContext(metadata, metadataProvider);
var adapter = new CompareAttributeAdapter(attribute);
// Act
var rules = adapter.GetClientValidationRules(context);
// Assert
var rule = Assert.Single(rules);
Assert.Equal("'MyPropertyDisplayName' and 'OtherPropertyDisplayName' do not match.", rule.ErrorMessage);
}
[Fact]
[ReplaceCulture]
public void ClientRulesWithCompareAttribute_ErrorMessageUsesPropertyName()
{
// Arrange
var metadataProvider = new DataAnnotationsModelMetadataProvider();
var metadata = metadataProvider.GetMetadataForProperty(() => null, typeof(PropertyNameModel), "MyProperty");
var attribute = new CompareAttribute("OtherProperty");
var context = new ClientModelValidationContext(metadata, metadataProvider);
var adapter = new CompareAttributeAdapter(attribute);
// Act
var rules = adapter.GetClientValidationRules(context);
// Assert
var rule = Assert.Single(rules);
Assert.Equal("'MyProperty' and 'OtherProperty' do not match.", rule.ErrorMessage);
}
[Fact]
public void ClientRulesWithCompareAttribute_ErrorMessageUsesOverride()
{
// Arrange
var metadataProvider = new DataAnnotationsModelMetadataProvider();
var metadata = metadataProvider.GetMetadataForProperty(() => null, typeof(PropertyNameModel), "MyProperty");
var attribute = new CompareAttribute("OtherProperty")
{
ErrorMessage = "Hello '{0}', goodbye '{1}'."
};
var context = new ClientModelValidationContext(metadata, metadataProvider);
var adapter = new CompareAttributeAdapter(attribute);
// Act
var rules = adapter.GetClientValidationRules(context);
// Assert
var rule = Assert.Single(rules);
Assert.Equal("Hello 'MyProperty', goodbye 'OtherProperty'.", rule.ErrorMessage);
}
[Fact]
public void ClientRulesWithCompareAttribute_ErrorMessageUsesResourceOverride()
{
// Arrange
var metadataProvider = new DataAnnotationsModelMetadataProvider();
var metadata = metadataProvider.GetMetadataForProperty(() => null, typeof(PropertyNameModel), "MyProperty");
var attribute = new CompareAttribute("OtherProperty")
{
ErrorMessageResourceName = "CompareAttributeTestResource",
ErrorMessageResourceType = typeof(Test.Resources),
};
var context = new ClientModelValidationContext(metadata, metadataProvider);
var adapter = new CompareAttributeAdapter(attribute);
// Act
var rules = adapter.GetClientValidationRules(context);
// Assert
var rule = Assert.Single(rules);
Assert.Equal("Comparing MyProperty to OtherProperty.", rule.ErrorMessage);
}
private class PropertyDisplayNameModel
{
[Display(Name = "MyPropertyDisplayName")]
public string MyProperty { get; set; }
[Display(Name = "OtherPropertyDisplayName")]
public string OtherProperty { get; set; }
}
private class PropertyNameModel
{
public string MyProperty { get; set; }
public string OtherProperty { get; set; }
}
}
}