Skip to content
This repository has been archived by the owner on Dec 14, 2018. It is now read-only.

Commit

Permalink
Address #2526; remove use of a required validator when validating `[B…
Browse files Browse the repository at this point in the history
…indRequired]`

- only use MVC error message when `[BindRequired]` is violated
- update that error message to more clearly describe the problem
- enable all tests skipped due to dupe bug #2493
- update expectations of a few tests using the old messages

nits:
- rename `ModelBinding_MissingRequiredMember` to `ModelBinding_MissingBindRequiredMember`
- remove `<param>` description of removed `requiredValidator` parameter
- remove unused `MutableObjectModelBinderTest.GetRequiredValidator()`
  • Loading branch information
dougbu committed Jun 5, 2015
1 parent cda2c67 commit eefa582
Show file tree
Hide file tree
Showing 7 changed files with 74 additions and 105 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
Expand Down Expand Up @@ -364,42 +363,19 @@ internal ModelValidationNode ProcessDto(
var modelExplorer = metadataProvider.GetModelExplorerForType(bindingContext.ModelType, bindingContext.Model);
var validationInfo = GetPropertyValidationInfo(bindingContext);

// Eliminate provided properties from requiredProperties; leaving just *missing* required properties.
// Eliminate provided properties from RequiredProperties; leaving just *missing* required properties.
var boundProperties = dto.Results.Where(p => p.Value.IsModelSet).Select(p => p.Key.PropertyName);
validationInfo.RequiredProperties.ExceptWith(boundProperties);

foreach (var missingRequiredProperty in validationInfo.RequiredProperties)
{
var addedError = false;

// We want to provide the 'null' value, not the value of model.Property,
// so avoiding modelExplorer.GetProperty here which would call the actual getter on the
// model. This avoids issues with value types, or properties with pre-initialized values.
var propertyExplorer = modelExplorer.GetExplorerForProperty(missingRequiredProperty, model: null);

var propertyExplorer = modelExplorer.GetExplorerForProperty(missingRequiredProperty);
var propertyName = propertyExplorer.Metadata.BinderModelName ?? missingRequiredProperty;
var modelStateKey = ModelNames.CreatePropertyModelName(
bindingContext.ModelName,
propertyName);

// Get the first 'required' validator (if any) to get custom error message.
var validatorProviderContext = new ModelValidatorProviderContext(propertyExplorer.Metadata);
bindingContext.OperationBindingContext.ValidatorProvider.GetValidators(validatorProviderContext);
var validator = validatorProviderContext.Validators.FirstOrDefault(v => v.IsRequired);
var modelStateKey = ModelNames.CreatePropertyModelName(bindingContext.ModelName, propertyName);

if (validator != null)
{
addedError = RunValidator(validator, bindingContext, propertyExplorer, modelStateKey);
}

// Fall back to default message if BindingBehaviorAttribute required this property and we have no
// actual validator for it.
if (!addedError)
{
bindingContext.ModelState.TryAddModelError(
modelStateKey,
Resources.FormatModelBinding_MissingRequiredMember(propertyName));
}
bindingContext.ModelState.TryAddModelError(
modelStateKey,
Resources.FormatModelBinding_MissingBindRequiredMember(propertyName));
}

// For each property that ComplexModelDtoModelBinder attempted to bind, call the setter, recording
Expand Down Expand Up @@ -436,10 +412,6 @@ internal ModelValidationNode ProcessDto(
/// </param>
/// <param name="propertyMetadata">The <see cref="ModelMetadata"/> for the property to set.</param>
/// <param name="dtoResult">The <see cref="ModelBindingResult"/> for the property's new value.</param>
/// <param name="requiredValidator">
/// The <see cref="IModelValidator"/> which ensures the value is not <c>null</c>. Or <c>null</c> if no such
/// requirement exists.
/// </param>
/// <remarks>Should succeed in all cases that <see cref="CanUpdateProperty"/> returns <c>true</c>.</remarks>
protected virtual void SetProperty(
[NotNull] ModelBindingContext bindingContext,
Expand Down
12 changes: 6 additions & 6 deletions src/Microsoft.AspNet.Mvc.Core/Properties/Resources.Designer.cs

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

58 changes: 29 additions & 29 deletions src/Microsoft.AspNet.Mvc.Core/Resources.resx
Original file line number Diff line number Diff line change
@@ -1,17 +1,17 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
<!--
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
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>
Expand All @@ -26,36 +26,36 @@
<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
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
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
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
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
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
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
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
Expand Down Expand Up @@ -499,8 +499,8 @@
<data name="ModelBinderUtil_ValueInvalidGeneric" xml:space="preserve">
<value>The supplied value is invalid for {0}.</value>
</data>
<data name="ModelBinding_MissingRequiredMember" xml:space="preserve">
<value>The '{0}' property is required.</value>
<data name="ModelBinding_MissingBindRequiredMember" xml:space="preserve">
<value>A value for the '{0}' property was not provided.</value>
</data>
<data name="ModelBinding_ValueRequired" xml:space="preserve">
<value>A value is required.</value>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -793,7 +793,7 @@ public void ProcessDto_BindRequiredFieldMissing_RaisesModelError()
var modelError = Assert.Single(modelState.Errors);
Assert.Null(modelError.Exception);
Assert.NotNull(modelError.ErrorMessage);
Assert.Equal("The 'Age' property is required.", modelError.ErrorMessage);
Assert.Equal("A value for the 'Age' property was not provided.", modelError.ErrorMessage);
}

[Fact]
Expand Down Expand Up @@ -844,7 +844,7 @@ public void ProcessDto_DataMemberIsRequiredFieldMissing_RaisesModelError()
var modelError = Assert.Single(modelState.Errors);
Assert.Null(modelError.Exception);
Assert.NotNull(modelError.ErrorMessage);
Assert.Equal("The 'Age' property is required.", modelError.ErrorMessage);
Assert.Equal("A value for the 'Age' property was not provided.", modelError.ErrorMessage);
}

[Fact]
Expand Down Expand Up @@ -1147,9 +1147,9 @@ public void ProcessDto_ProvideRequiredFields_Success()
Assert.Equal(0m, model.PropertyWithDefaultValue); // [DefaultValue] has no effect
}

// This uses [Required] with [BindRequired] to provide a custom validation messsage.
// [Required] cannot provide a custom validation for [BindRequired] errors.
[Fact]
public void ProcessDto_ValueTypePropertyWithBindRequired_CustomValidationMessage()
public void ProcessDto_ValueTypePropertyWithBindRequired_RequiredValidatorIgnored()
{
// Arrange
var model = new ModelWithBindRequiredAndRequiredAttribute();
Expand Down Expand Up @@ -1191,16 +1191,16 @@ public void ProcessDto_ValueTypePropertyWithBindRequired_CustomValidationMessage
.Value;
var error = Assert.Single(entry.Errors);
Assert.Null(error.Exception);
Assert.Equal("Custom Message ValueTypeProperty", error.ErrorMessage);
Assert.Equal("A value for the 'ValueTypeProperty' property was not provided.", error.ErrorMessage);

// Model gets provided values.
Assert.Equal(0, model.ValueTypeProperty);
Assert.Equal("value", model.ReferenceTypeProperty);
}

// This uses [Required] with [BindRequired] to provide a custom validation messsage.
// [Required] cannot provide a custom validation for [BindRequired] errors.
[Fact]
public void ProcessDto_ReferenceTypePropertyWithBindRequired_CustomValidationMessage()
public void ProcessDto_ReferenceTypePropertyWithBindRequired_RequiredValidatorIgnored()
{
// Arrange
var model = new ModelWithBindRequiredAndRequiredAttribute();
Expand Down Expand Up @@ -1242,7 +1242,7 @@ public void ProcessDto_ReferenceTypePropertyWithBindRequired_CustomValidationMes
.Value;
var error = Assert.Single(entry.Errors);
Assert.Null(error.Exception);
Assert.Equal("Custom Message ReferenceTypeProperty", error.ErrorMessage);
Assert.Equal("A value for the 'ReferenceTypeProperty' property was not provided.", error.ErrorMessage);

// Model gets provided values.
Assert.Equal(17, model.ValueTypeProperty);
Expand Down Expand Up @@ -1715,15 +1715,6 @@ private static ModelBindingContext CreateContext(ModelMetadata metadata, object
};
}

private static IModelValidator GetRequiredValidator(ModelBindingContext bindingContext, ModelMetadata propertyMetadata)
{
var validatorProvider = bindingContext.OperationBindingContext.ValidatorProvider;
var validatorProviderContext = new ModelValidatorProviderContext(propertyMetadata);
validatorProvider.GetValidators(validatorProviderContext);

return validatorProviderContext.Validators.FirstOrDefault(v => v.IsRequired);
}

private static ModelMetadata GetMetadataForCanUpdateProperty(string propertyName)
{
var metadataProvider = TestModelMetadataProvider.CreateDefaultProvider();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,10 +49,14 @@ public async Task BindingBehavior_MissingRequiredProperties_ValidationErrors()
Assert.Equal(2, errors.Count);

var error = Assert.Single(errors, kvp => kvp.Key == "model.BehaviourRequiredProperty");
Assert.Equal("The 'BehaviourRequiredProperty' property is required.", ((JArray)error.Value)[0].Value<string>());
Assert.Equal(
"A value for the 'BehaviourRequiredProperty' property was not provided.",
((JArray)error.Value)[0].Value<string>());

error = Assert.Single(errors, kvp => kvp.Key == "model.BindRequiredProperty");
Assert.Equal("The 'BindRequiredProperty' property is required.", ((JArray)error.Value)[0].Value<string>());
Assert.Equal(
"A value for the 'BindRequiredProperty' property was not provided.",
((JArray)error.Value)[0].Value<string>());
}

[Fact]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,9 @@ public async Task DataMember_MissingRequiredProperty_ValidationError()
Assert.Equal(1, errors.Count);

var error = Assert.Single(errors, kvp => kvp.Key == "model.RequiredProperty");
Assert.Equal("The 'RequiredProperty' property is required.", ((JArray)error.Value)[0].Value<string>());
Assert.Equal(
"A value for the 'RequiredProperty' property was not provided.",
((JArray)error.Value)[0].Value<string>());
}

[Fact]
Expand Down
Loading

0 comments on commit eefa582

Please sign in to comment.