Skip to content

Commit

Permalink
Add fluentvalidation for child properties
Browse files Browse the repository at this point in the history
  • Loading branch information
Thomas Brenna committed Mar 12, 2024
1 parent 4589036 commit d9e5357
Show file tree
Hide file tree
Showing 5 changed files with 50 additions and 23 deletions.
2 changes: 1 addition & 1 deletion testss.ServiceInterface/MyServices.cs
Expand Up @@ -6,7 +6,7 @@ namespace testss.ServiceInterface;

public class MyServices : Service
{
public object Any(MyListRequest request)
public object Post(MyListRequest request)
{
var l = new List<string>();

Expand Down
21 changes: 0 additions & 21 deletions testss.ServiceModel/GetList.cs

This file was deleted.

2 changes: 2 additions & 0 deletions testss.ServiceModel/ListEntry.cs
Expand Up @@ -26,5 +26,7 @@ public ListEntryValidator()
RuleFor(h => h.Prop2).Must(t => t >= 10).WithMessage("Prop2 must be at least 10!");

RuleFor(h => h.Child).NotEmpty().WithMessage("Child cannot be empty!");

RuleFor(h => h.Child).SetValidator(new ListEntryChildValidator());
}
}
12 changes: 11 additions & 1 deletion testss.ServiceModel/ListEntryChild.cs
@@ -1,4 +1,5 @@
using ServiceStack;
using ServiceStack.FluentValidation;
using System;
using System.Collections.Generic;
using System.Linq;
Expand All @@ -9,6 +10,15 @@ namespace testss.ServiceModel;

public class ListEntryChild
{
[ValidateNotEmpty]
public required string ChildProp { get; set; }
}

public class ListEntryChildValidator : AbstractValidator<ListEntryChild>
{
public ListEntryChildValidator()
{
RuleFor(lec => lec.ChildProp).NotEmpty().WithMessage("ChildProp cannot be empty!");

RuleFor(lec => lec.ChildProp).Must(p => p == "MUST BE THIS").WithMessage("ChildProp must be one of: 'MUST BE THIS'");
}
}
36 changes: 36 additions & 0 deletions testss.ServiceModel/MyListRequest.cs
@@ -0,0 +1,36 @@
using ServiceStack;

using ServiceStack.FluentValidation;
using ServiceStack.FluentValidation.Results;
using System.Collections.Generic;

namespace testss.ServiceModel;

[Route("/list")]
public class MyListRequest : IPost, IReturn<MyListResponse>
{
public required List<ListEntry> Entries { get; set; }
}

public class MyListResponse
{
public required List<string> Result { get; set; }

public ResponseStatus ResponseStatus { get; set; }
}

public class MyListRequestValidator : AbstractValidator<MyListRequest>
{
public MyListRequestValidator()
{
RuleFor(mlr => mlr).NotNull().WithMessage("Empty request");
RuleFor(mlr => mlr.Entries).NotNull().WithMessage("Expected property 'Entries' not found");

When(mlr => mlr.Entries != null, () =>
{
RuleFor(mlr => mlr.Entries.Count).Must(c => c >= 1).WithMessage("MyListRequest must contain at least 1 entry");
});

RuleForEach(mlr => mlr.Entries).SetValidator(new ListEntryValidator());
}
}

0 comments on commit d9e5357

Please sign in to comment.