Skip to content

Commit 28e28b4

Browse files
authored
ChipField: Check chips for Required validation (#660)
* Add unit test for required chip field validation * Update script reference for MudExtensions to minified version * Add validation button to required chip field test * Replace MultiSelectTestRequiredValue and DebounceTextFieldTest with ChipFieldRequiredTest in Index.razor * Refactor ChipField to use ChipFieldTextField for improved validation and add required chip validation tests * Add tests for required chip validation with null values and text input
1 parent 846dc4b commit 28e28b4

7 files changed

Lines changed: 193 additions & 6 deletions

File tree

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
using System.ComponentModel;
2+
using Microsoft.AspNetCore.Components;
3+
4+
namespace MudExtensions
5+
{
6+
/// <summary>
7+
/// The text field rendered inside <see cref="MudChipField{T}"/>. It validates Required against the chips of
8+
/// the chip field instead of the typed text, so it agrees with the chip field's own validation.
9+
/// It is public only because Razor can't render internal components; it isn't meant to be used directly.
10+
/// </summary>
11+
/// <typeparam name="T"></typeparam>
12+
[EditorBrowsable(EditorBrowsableState.Never)]
13+
public sealed class ChipFieldTextField<T> : MudTextFieldExtended<T>
14+
{
15+
/// <summary>
16+
/// Returns true when the parent chip field has at least one chip.
17+
/// </summary>
18+
[Parameter]
19+
public Func<bool>? HasChips { get; set; }
20+
21+
/// <inheritdoc />
22+
protected override bool HasValue(T? value) => HasChips?.Invoke() ?? base.HasValue(value);
23+
}
24+
}

‎src/CodeBeam.MudBlazor.Extensions/Components/ChipField/MudChipField.razor‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,9 @@
22
@inherits MudTextFieldExtended<T>
33
@typeparam T
44

5-
<MudTextFieldExtended @ref="_textFieldExtendedReference"
5+
<ChipFieldTextField @ref="_textFieldExtendedReference"
66
T="T"
7+
HasChips="@_hasChips"
78
Immediate="true"
89
OnKeyDown="HandleKeyDown"
910
OnKeyUp="HandleKeyUp"
@@ -63,4 +64,4 @@
6364
@AdornmentEnd
6465
</AdornmentEnd>
6566

66-
</MudTextFieldExtended>
67+
</ChipFieldTextField>

‎src/CodeBeam.MudBlazor.Extensions/Components/ChipField/MudChipField.razor.cs‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,9 +21,11 @@ public MudChipField()
2121
_valuesState = registerScope.RegisterParameter<List<string>?>(nameof(Values))
2222
.WithParameter(() => Values)
2323
.WithEventCallback(() => ValuesChanged);
24+
_hasChips = () => HasValue(default);
2425
}
2526

2627
private readonly ParameterState<List<string>?> _valuesState;
28+
private readonly Func<bool> _hasChips;
2729

2830
/// <summary>
2931
/// Protected classes.
@@ -285,6 +287,13 @@ public async Task Closed(MudChip<T> chip)
285287
await _textFieldExtendedReference.FocusAsync();
286288
}
287289

290+
/// <summary>
291+
/// The chip field has a value when it has at least one chip, so Required checks the chips instead of the typed text.
292+
/// </summary>
293+
/// <param name="value"></param>
294+
/// <returns></returns>
295+
protected override bool HasValue(T? value) => _valuesState.Value is { Count: > 0 };
296+
288297
/// <summary>
289298
/// Clear the text field.
290299
/// </summary>

‎tests/CodeBeam.MudBlazor.Extensions.UnitTests.Viewer/Pages/Index.razor‎

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,4 @@
66

77
Welcome to your new app.
88

9-
<MudExtensions.UnitTests.TestComponents.MultiSelectTestRequiredValue />
10-
11-
<MudExtensions.UnitTests.TestComponents.DebounceTextFieldTest />
9+
<MudExtensions.UnitTests.TestComponents.ChipFieldRequiredTest />
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
@namespace MudExtensions.UnitTests.TestComponents
2+
3+
<MudForm @ref="Form">
4+
<MudChipField T="string" @bind-Values="Values" Label="Chip Field" Required="true" RequiredError="Add at least one chip" Variant="Variant.Outlined" />
5+
<MudButton Variant="Variant.Filled" Color="Color.Primary" OnClick="@(() => Form?.Validate())">Validate</MudButton>
6+
</MudForm>
7+
8+
@code {
9+
public static string __description__ = "A required chip field should be valid when it has chips, even if its text input is empty";
10+
11+
public MudForm? Form { get; private set; }
12+
13+
[Parameter]
14+
public List<string>? Values { get; set; }
15+
}

‎tests/CodeBeam.MudBlazor.Extensions.UnitTests.Viewer/wwwroot/index.html‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@
3030
</div>
3131
<script src="_framework/blazor.webassembly.js"></script>
3232
<script src="_content/MudBlazor/MudBlazor.min.js"></script>
33-
<script src="_content/CodeBeam.MudBlazor.Extensions/MudExtensions.js"></script>
33+
<script src="_content/CodeBeam.MudBlazor.Extensions/MudExtensions.min.js"></script>
3434
</body>
3535

3636
</html>

‎tests/CodeBeam.MudBlazor.Extensions.UnitTests/Components/ChipFieldTests.cs‎

Lines changed: 140 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
using Bunit;
22
using AwesomeAssertions;
33
using Microsoft.AspNetCore.Components;
4+
using Microsoft.AspNetCore.Components.Web;
45
using MudBlazor;
56
using MudBlazor.Extensions;
67
using MudExtensions.UnitTests.TestComponents;
@@ -54,5 +55,144 @@ public async Task ChipField_ParentFormReadOnly_ShouldPreventRemoval()
5455
await comp.InvokeAsync(() => chipField.Instance.Closed(chips[0].Instance));
5556
chipField.Instance.GetState(x => x.Values).Should().BeEquivalentTo(new List<string> { "first", "second" });
5657
}
58+
59+
[Test]
60+
public async Task ChipField_Required_WithChips_ShouldBeValid()
61+
{
62+
var comp = Context.Render<ChipFieldRequiredTest>(opt =>
63+
{
64+
opt.Add(a => a.Values, new List<string> { "first" });
65+
});
66+
67+
await comp.InvokeAsync(() => comp.Instance.Form!.Validate());
68+
69+
comp.Instance.Form!.IsValid.Should().BeTrue();
70+
comp.Instance.Form.Errors.Should().BeEmpty();
71+
comp.FindAll(".mud-input-error").Should().BeEmpty();
72+
comp.Markup.Should().NotContain("Add at least one chip");
73+
}
74+
75+
[Test]
76+
public async Task ChipField_Required_WithoutChips_ShouldBeInvalid()
77+
{
78+
var comp = Context.Render<ChipFieldRequiredTest>(opt =>
79+
{
80+
opt.Add(a => a.Values, new List<string>());
81+
});
82+
83+
await comp.InvokeAsync(() => comp.Instance.Form!.Validate());
84+
85+
comp.Instance.Form!.IsValid.Should().BeFalse();
86+
comp.Instance.Form.Errors.Should().ContainSingle().Which.Should().Be("Add at least one chip");
87+
comp.Markup.Should().Contain("Add at least one chip");
88+
}
89+
90+
[Test]
91+
public async Task ChipField_Required_WithTextButNoChips_ShouldBeInvalid()
92+
{
93+
var comp = Context.Render<ChipFieldRequiredTest>(opt =>
94+
{
95+
opt.Add(a => a.Values, new List<string>());
96+
});
97+
98+
comp.Find("input").Input(new ChangeEventArgs { Value = "not a chip yet" });
99+
await comp.InvokeAsync(() => comp.Instance.Form!.Validate());
100+
101+
comp.Instance.Form!.IsValid.Should().BeFalse();
102+
}
103+
104+
[Test]
105+
public async Task ChipField_Required_TypingAfterError_ShouldKeepShowingError()
106+
{
107+
var comp = Context.Render<ChipFieldRequiredTest>(opt =>
108+
{
109+
opt.Add(a => a.Values, new List<string>());
110+
});
111+
await comp.InvokeAsync(() => comp.Instance.Form!.Validate());
112+
comp.Markup.Should().Contain("Add at least one chip");
113+
114+
comp.Find("input").Input(new ChangeEventArgs { Value = "not a chip yet" });
115+
comp.Markup.Should().Contain("Add at least one chip");
116+
117+
await comp.InvokeAsync(() => comp.Instance.Form!.Validate());
118+
119+
comp.Instance.Form!.IsValid.Should().BeFalse();
120+
comp.Markup.Should().Contain("Add at least one chip");
121+
comp.Find("input").GetAttribute("aria-invalid").Should().Be("true");
122+
}
123+
124+
[Test]
125+
public async Task ChipField_Required_AddingChipAfterError_ShouldBecomeValid()
126+
{
127+
var comp = Context.Render<ChipFieldRequiredTest>(opt =>
128+
{
129+
opt.Add(a => a.Values, new List<string>());
130+
});
131+
await comp.InvokeAsync(() => comp.Instance.Form!.Validate());
132+
comp.Instance.Form!.IsValid.Should().BeFalse();
133+
134+
var chipField = comp.FindComponent<MudChipField<string>>();
135+
comp.Find("input").Input(new ChangeEventArgs { Value = "first" });
136+
await comp.InvokeAsync(() => chipField.Instance.HandleBeforeInput(new BeforeInputEventArgs { Data = " ", InputType = "insert" }));
137+
chipField.Instance.GetState(x => x.Values).Should().BeEquivalentTo(new List<string> { "first" });
138+
139+
await comp.InvokeAsync(() => comp.Instance.Form!.Validate());
140+
141+
comp.Instance.Form!.IsValid.Should().BeTrue();
142+
comp.FindAll(".mud-input-error").Should().BeEmpty();
143+
comp.Markup.Should().NotContain("Add at least one chip");
144+
}
145+
146+
[Test]
147+
public async Task ChipField_Required_BlurWithChips_ShouldNotShowError()
148+
{
149+
var comp = Context.Render<ChipFieldRequiredTest>(opt =>
150+
{
151+
opt.Add(a => a.Values, new List<string> { "first" });
152+
});
153+
154+
await comp.Find("input").BlurAsync(new FocusEventArgs());
155+
156+
comp.FindAll(".mud-input-error").Should().BeEmpty();
157+
comp.Instance.Form!.Errors.Should().BeEmpty();
158+
}
159+
160+
[Test]
161+
public void ChipField_Required_ShouldKeepRequiredMarker()
162+
{
163+
var comp = Context.Render<ChipFieldRequiredTest>(opt =>
164+
{
165+
opt.Add(a => a.Values, new List<string> { "first" });
166+
});
167+
168+
comp.FindAll(".mud-input-control.mud-input-required").Should().NotBeEmpty();
169+
}
170+
171+
[Test]
172+
public async Task ChipField_Required_WithNullValues_ShouldBeInvalid()
173+
{
174+
var comp = Context.Render<ChipFieldRequiredTest>();
175+
176+
await comp.InvokeAsync(() => comp.Instance.Form!.Validate());
177+
178+
comp.Instance.Form!.IsValid.Should().BeFalse();
179+
comp.Markup.Should().Contain("Add at least one chip");
180+
}
181+
182+
[Test]
183+
public async Task ChipFieldTextField_WithoutHasChips_ShouldValidateRequiredAgainstText()
184+
{
185+
var comp = Context.Render<ChipFieldTextField<string>>(opt =>
186+
{
187+
opt.Add(a => a.Required, true);
188+
});
189+
190+
await comp.InvokeAsync(() => comp.Instance.ValidateAsync());
191+
comp.Instance.HasErrors.Should().BeTrue();
192+
193+
comp.Find("input").Change("text");
194+
await comp.InvokeAsync(() => comp.Instance.ValidateAsync());
195+
comp.Instance.HasErrors.Should().BeFalse();
196+
}
57197
}
58198
}

0 commit comments

Comments
 (0)