'ASP.NET Core Web API - 'IRuleBuilderInitial<CustomerTransactionRequestDto, decimal>' does not contain a definition for 'CustomCurrency'
Validation is done in ASP.NET Core-6 Web API using Fluent Validation. So, I have this code:
Custom Validator:
public static IRuleBuilder<T, string> CustomCurrency<T>(this IRuleBuilder<T, string> ruleBuilder)
{
var options = ruleBuilder
.Matches(@"^\d+.\d{1,2}$")
.WithMessage("Appropriate Currency format should be xxxxxxxxxxx.xx");
return options;
}
DTO:
public class CustomerTransactionRequestDto
{
public decimal Amount { get; set; }
}
Then the validator:
public class CustomerTransactionRequestValidator : AbstractValidator<CustomerTransactionRequestDto>
{
public CustomerTransactionRequestValidator()
{
RuleFor(p => p.Amount).CustomCurrency()
.NotEmpty().WithMessage("Amount should be not empty. ERROR!");
}
}
The problem is that I got this error:
Error CS1929 'IRuleBuilderInitial<CustomerTransactionRequestDto, decimal>' does not contain a definition for 'CustomCurrency' and the best extension method overload 'AuthValidatorSettings.CustomCurrency(IRuleBuilder<CustomerTransactionRequestDto, string>)' requires a receiver of type 'IRuleBuilder<CustomerTransactionRequestDto, string>'
Then it highlights:
RuleFor(p => p.Amount)
How do I get this sorted out?
Thank you
Solution 1:[1]
The error message hints that types don't match. You have a custom validator based on IRuleBuilder<T, string> while you are trying to chain it to IRuleBuilderInitial<CustomerTransactionRequestDto, decimal>. You have a custom validator based on string property, while on the other end a decimal property.
To fix this, change the type of Amount property from decimal to string:
public class CustomerTransactionRequestDto
{
public string Amount { get; set; }
}
That way, you can use the validators you already defined in CustomCurrency() like Matches() which are available for string properties.
If decimal property is not a mistake, then I'd suggest adding support for decimal in CustomCurrency() custom validator, like this:
public static IRuleBuilder<T, decimal> CustomCurrency<T>(this IRuleBuilder<T, decimal> ruleBuilder)
{
// TODO: Your validation.
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Prolog |
