Skip to content

Commit 41c1c5c

Browse files
committed
Started adding support for nested object validation in blazor.
1 parent 40eb46c commit 41c1c5c

File tree

2 files changed

+77
-0
lines changed

2 files changed

+77
-0
lines changed
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
@using Microsoft.AspNetCore.Components.Forms
2+
@implements IDisposable
3+
4+
<CascadingValue Value="EditContext" IsFixed="true">
5+
<DataAnnotationsValidator />
6+
@ChildContent
7+
</CascadingValue>
8+
9+
@code
10+
{
11+
[CascadingParameter]
12+
public required EditContext ParentEditContext { get; set; }
13+
14+
[Parameter]
15+
public required RenderFragment ChildContent { get; set; }
16+
17+
[Parameter]
18+
public required object Model { get; set; }
19+
20+
[Parameter] public bool Validate { get; set; } = true;
21+
22+
private EditContext? _editContext;
23+
private ValidationMessageStore? _messageStore;
24+
private ValidationMessageStore? _parentMessageStore;
25+
public EditContext EditContext => _editContext ??= new EditContext(Model);
26+
27+
protected override void OnInitialized()
28+
{
29+
base.OnInitialized();
30+
ParentEditContext.OnValidationRequested += ParentEditContextOnOnValidationRequested;
31+
_messageStore = new ValidationMessageStore(EditContext);
32+
_parentMessageStore = new ValidationMessageStore(ParentEditContext);
33+
}
34+
35+
private void ParentEditContextOnOnValidationRequested(object? sender, ValidationRequestedEventArgs e)
36+
{
37+
_messageStore?.Clear();
38+
_parentMessageStore?.Clear();
39+
if (!Validate)
40+
{
41+
return;
42+
}
43+
if (!EditContext.Validate())
44+
{
45+
_parentMessageStore?.Add(() => Model, "Invalid");
46+
}
47+
}
48+
49+
public void Dispose()
50+
{
51+
ParentEditContext.OnValidationRequested -= ParentEditContextOnOnValidationRequested;
52+
}
53+
}
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
namespace DotNetElements.Core.Validation;
2+
3+
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)]
4+
public sealed class ValidateObjectAttribute : ValidationAttribute
5+
{
6+
public ValidateObjectAttribute()
7+
: base("Nested item is not valid.")
8+
{
9+
}
10+
11+
protected override ValidationResult? IsValid(object? value, ValidationContext validationContext)
12+
{
13+
if (value is null)
14+
return ValidationResult.Success;
15+
16+
ValidationContext context = new(value, validationContext, null);
17+
List<ValidationResult> results = [];
18+
19+
if (!Validator.TryValidateObject(value, context, results, validateAllProperties: true))
20+
return new ValidationResult(ErrorMessage, validationContext.MemberName is not null ? [validationContext.MemberName] : null);
21+
22+
return ValidationResult.Success;
23+
}
24+
}

0 commit comments

Comments
 (0)