How to validate if Status exists in my static class?
public static class AppConstants
{
public static class FormStatus
{
public static string NEW = "New";
public static string COMPLETE = "Complete";
public static string DELETED = "Deleted";
}
}
Validator class
public SetStatusCommandValidator(IApplicationDbContext context)
{
_context = context;
RuleFor(v => v.Status)
.NotNull()
.NotEmpty().WithMessage("Status is required.")
.Must(???).WithMessage("Status is not a valid.");
}
Basically, how do I validate that the status' values must be one of the AppConstants.FormStatus?
Thanks!
You can create a collection / array inline in the Must
predicate and use .Contains
:
RuleFor(v => v.Status)
.NotNull()
.NotEmpty().WithMessage(...)
.Must(v => new [] { AppConstants.FormStatus.NEW, AppConstants.FormStatus.COMPLETE, AppConstants.FormStatus.DELETED }.Contains(v)).WithMessage(...);
Alternatively, you can add another property to FormStatus
that contains all of them:
public static class AppConstants
{
public static class FormStatus
{
// Statuses here
public static string[] ALL_STATUSES = new string[] { NEW, COMPLETE, DELETED };
}
}
Then your Must
predicate becomes Must(v => AppConstants.FormStatus.ALL_STATUSES.Contains(v)).WithMessage(...);
Sorry if the syntax isn't exactly right and doesn't compile right away, I wrote it on my phone with no way to double check it.