I want to make a rule with Fluent Validation that checks: if this field contains a Credit Card number then it is invalid (because it contains sensitive data)
Seems easy.
Fluent Validation provides CreditCard()
check, but it's the opposite of what i'm trying to do, i searched if there is some kind of negation, like .Not().CreditCard()
or .NotMatch()
, but i couldn't find.
There is the idea of making a RegExp that will not match only when the field contains a valid credit card, but it seems very unintuitive and unreadable, i wander if there is a more straight forward solution.
CodePudding user response:
CreditCardValidator is given for a purpose so that we can avoid saving/processing invalid CreditCard. but with your requirement it seems you would allow to save/process invalid creditcard but will block user for giving valid data.
I am not able to get what is real use case here. could please clarify your usecase.
Update:
you could do something like this.
public class MyCreditCardValidator<T> : CreditCardValidator<T>
{
public override bool IsValid(ValidationContext<T> context, string value)
{
bool validCreditCard = base.IsValid(context, value);
// for my case i want invalid credit card
return !validCreditCard;
}
protected override string GetDefaultMessageTemplate(string errorCode)
{
return "field contains credit card";
}
}
and add extension method like
public static class CustomerValidatorExtensions
{
public static IRuleBuilderOptions<T, string> NotACreditCard<T>(this IRuleBuilder<T, string> ruleBuilder)
{
return ruleBuilder.SetValidator(new MyCreditCardValidator<T>());
}
}
and call like this
public CustomerValidator()
{
RuleFor(a => a.Notes).NotACreditCard();
}
now when you provide valid creditcard in the notes field it will fail the validation and return your the error
Hope this helpful.