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.
Since you're not using an Enum (which would allow you to use .IsEnumName()
), I think you need to create a custom validator function:
private bool BeAValidStatus(string status)
{
return typeof(AppConstants.FormStatus)
.GetFields(BindingFlags.Static | BindingFlags.Public)
.Where(f => f.GetRawConstantValue() == status)
.Any();
}
Then use the custom function in a rule:
RuleFor(v => v.Status)
.NotNull()
.NotEmpty().WithMessage("Status is required.")
.Must(BeAValidStatus).WithMessage("Status is not a valid.");
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.