-2

I have a class called Transaction which contains a property named source

Within the Transaction class I have some validation using FluentValidation, I am currently trying to validate the source property using regex however I'm having an issue

    //source isnt required but when present must be 1 character 'X' or 'Y'
    RuleFor(transaction => transacion.source)
        .Matches("^(X|Y)?$")
        .When(Transaction => transaction.source != null);

I am getting:

Error 1 FluentValidation.IRuleBuilderInitial<MyUtility.Transaction,char?> does not contain a definition for 'Matches' and the best extension method overload FluentValidation.DefaultValidatorExtensions.Matches<T>(FluentValidation.IRuleBuilder<T,string>, System.Text.RegularExpressions.Regex) has some invalid arguments

I have just used this exact same code for a different property with no problems, although that was a string not a char.

JsonStatham
  • 9,770
  • 27
  • 100
  • 181
  • 2
    Don't think that's your issue, but FYI `(X|Y)` is `[XY]` (quicker to search and possibly easier to read) – Robin Apr 14 '14 at 09:47

1 Answers1

4

There's an extra dot . in your code between Matches and ("^(X|Y)?$").

.RuleFor(transaction => transaction.source)
    .Matches("^(X|Y)?$") // dot was here
    .When(transaction => transaction.source != null);

And as Robin pointed out, the regex is more readable in a [XY] format.

EDIT

I just reread your post and it says that the source property is a char so if you convert it to a string you won't get the error.

.RuleFor(transaction => transaction.source.HasValue ? transaction.source.ToString() : "")
    .Matches("^[XY]?$") // dot was here
    .When(transaction => transaction.source != null);
juan.facorro
  • 9,791
  • 2
  • 33
  • 41
  • Yes I realised this after I posted however still getting the same error message without it – JsonStatham Apr 14 '14 at 10:32
  • @juan-facorro How would the regex be written in te [XY] format? – JsonStatham Apr 14 '14 at 13:19
  • 1
    @SelectDistinct Just edited the answer with the `[XY]` format. – juan.facorro Apr 14 '14 at 14:11
  • @juan-facorro Unit tests are failing if source is null, which it may possibly be, as its a char it is failing when attempting to convert to string - Any suggestions? – JsonStatham Apr 15 '14 at 10:48
  • 1
    @SelectDistinct The solution for that is pretty straight-forward. Just test for `null` before calling `.ToString()` in the lambda expression for the `RuleFor` constructor: `.RuleFor(x => (x.source.HasValue ? x.source.ToString() : ""))`. – juan.facorro Apr 15 '14 at 14:48