Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 8 additions & 1 deletion src/Components/Forms/src/EditContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -90,10 +90,17 @@ public FieldIdentifier Field(string fieldName)
/// <param name="fieldIdentifier">Identifies the field whose value has been changed.</param>
public void NotifyFieldChanged(in FieldIdentifier fieldIdentifier)
{
GetOrAddFieldState(fieldIdentifier).IsModified = true;
MarkAsModified(fieldIdentifier);
OnFieldChanged?.Invoke(this, new FieldChangedEventArgs(fieldIdentifier));
}

/// <summary>
/// Marks the specified field as modified.
/// </summary>
/// <param name="fieldIdentifier">Identifies the field whose modification flag should be set.</param>
public void MarkAsModified(in FieldIdentifier fieldIdentifier)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why this helper method is needed?

=> GetOrAddFieldState(fieldIdentifier).IsModified = true;

/// <summary>
/// Signals that some aspect of validation state has changed.
/// </summary>
Expand Down
1 change: 1 addition & 0 deletions src/Components/Forms/src/PublicAPI.Unshipped.txt
Original file line number Diff line number Diff line change
Expand Up @@ -12,3 +12,4 @@ Microsoft.AspNetCore.Components.Forms.EditContext.IsValidationPending() -> bool
Microsoft.AspNetCore.Components.Forms.EditContext.IsValidationFaulted(in Microsoft.AspNetCore.Components.Forms.FieldIdentifier fieldIdentifier) -> bool
Microsoft.AspNetCore.Components.Forms.EditContext.IsValidationFaulted<TField>(System.Linq.Expressions.Expression<System.Func<TField>!>! accessor) -> bool
Microsoft.AspNetCore.Components.Forms.EditContext.IsValidationFaulted() -> bool
Microsoft.AspNetCore.Components.Forms.EditContext.MarkAsModified(in Microsoft.AspNetCore.Components.Forms.FieldIdentifier fieldIdentifier) -> void
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,28 @@ public void PerformsPerPropertyValidationOnFieldChange()
Assert.Equal(new[] { "IntFrom1To100:range" }, editContext.GetValidationMessages());
}

[Fact]
public void MarkAsModifiedDoesNotTriggerPerPropertyValidation()
{
var model = new TestModel { IntFrom1To100 = 101 };
var editContext = new EditContext(model);
editContext.EnableDataAnnotationsValidation(_serviceProvider);
var onValidationStateChangedCount = 0;
var requiredStringIdentifier = new FieldIdentifier(model, nameof(TestModel.RequiredString));
editContext.OnValidationStateChanged += (sender, eventArgs) => onValidationStateChangedCount++;

editContext.MarkAsModified(requiredStringIdentifier);

Assert.True(editContext.IsModified(requiredStringIdentifier));
Assert.Equal(0, onValidationStateChangedCount);
Assert.Empty(editContext.GetValidationMessages(requiredStringIdentifier));
Assert.Empty(editContext.GetValidationMessages());

editContext.NotifyFieldChanged(requiredStringIdentifier);
Assert.Equal(1, onValidationStateChangedCount);
Assert.Equal(new[] { "RequiredString:required" }, editContext.GetValidationMessages());
}

[Theory]
[InlineData(nameof(TestModel.ThisWillNotBeValidatedBecauseItIsAField))]
[InlineData(nameof(TestModel.ThisWillNotBeValidatedBecauseItIsInternal))]
Expand Down
15 changes: 15 additions & 0 deletions src/Components/Forms/test/EditContextTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,21 @@ public void RaisesEventWhenFieldIsChanged()
Assert.True(didReceiveNotification);
}

[Fact]
public void MarkAsModifiedTracksFieldAsModifiedWithoutRaisingOnFieldChanged()
{
var editContext = new EditContext(new object());
var field1 = editContext.Field("field1");
var didReceiveNotification = false;
editContext.OnFieldChanged += (sender, eventArgs) => didReceiveNotification = true;

editContext.MarkAsModified(field1);

Assert.True(editContext.IsModified());
Assert.True(editContext.IsModified(field1));
Assert.False(didReceiveNotification);
}

[Fact]
public void CanEnumerateValidationMessagesAcrossAllStoresForSingleField()
{
Expand Down
18 changes: 15 additions & 3 deletions src/Components/Web/src/Forms/InputBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -115,18 +115,24 @@ protected string? CurrentValueAsString
{
_incomingValueBeforeParsing = value;
_parsingValidationMessages?.Clear();
var previousParsingAttemptFailed = _previousParsingAttemptFailed;
var notifyFieldChangedOnSuccessfulRecovery = false;

if (_nullableUnderlyingType != null && string.IsNullOrEmpty(value))
{
// Assume if it's a nullable type, null/empty inputs should correspond to default(T)
// Then all subclasses get nullable support almost automatically (they just have to
// not reject Nullable<T> based on the type itself).
_parsingFailed = false;
notifyFieldChangedOnSuccessfulRecovery = previousParsingAttemptFailed && EqualityComparer<TValue>.Default.Equals(default, Value);
_previousParsingAttemptFailed = false;
CurrentValue = default!;
}
else if (TryParseValueFromString(value, out var parsedValue, out var validationErrorMessage))
{
_parsingFailed = false;
notifyFieldChangedOnSuccessfulRecovery = previousParsingAttemptFailed && EqualityComparer<TValue>.Default.Equals(parsedValue, Value);
_previousParsingAttemptFailed = false;
CurrentValue = parsedValue!;
}
else
Expand All @@ -139,13 +145,19 @@ protected string? CurrentValueAsString
_parsingValidationMessages ??= new ValidationMessageStore(EditContext);
_parsingValidationMessages.Add(FieldIdentifier, validationErrorMessage);

// Since we're not writing to CurrentValue, we'll need to notify about modification from here
EditContext.NotifyFieldChanged(FieldIdentifier);
// The raw input changed, but the model value did not. Track the user interaction
// without revalidating the unchanged model value.
EditContext.MarkAsModified(FieldIdentifier);

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we also notify the field when parsing successfully recovers to the same model value? For a [Required] int? that starts null, the sequence null -> "1e+10" -> empty clears the parsing message, but assigning null hits CurrentValue's equality gate and never raises NotifyFieldChanged. The model remains null with no Required message, and the browser renders the field as modified valid.

The current E2E path enters 5 before the final empty value, so it only covers a value-changing recovery. Please add direct null -> invalid -> empty coverage and notify exactly once on successful recovery, while continuing to avoid model validation on the parse failure itself.

}
}

if (notifyFieldChangedOnSuccessfulRecovery)
{
EditContext?.NotifyFieldChanged(FieldIdentifier);
}

// We can skip the validation notification if we were previously valid and still are
if (_parsingFailed || _previousParsingAttemptFailed)
if (_parsingFailed || previousParsingAttemptFailed)
{
EditContext?.NotifyValidationStateChanged();
_previousParsingAttemptFailed = _parsingFailed;
Expand Down
Loading
Loading