Question

Following on from my previous question, I have a nullable char named source in my Transaction class.

    //source isnt required but when present must be 1 character 'I' or 'M'            
    RuleFor(transaction => transaction.source.ToString())
        .Matches("^[IM]?$")                
        .When(t => t.source.Value != null);

As Matches and When are not available for a char, I am using the .ToString() method however, if when a new Transaction object is generated, the source property is null, the application fails due to being unable to convert a null source to a string.

Can anyone suggest a way of running the validation for source ONLY if source is not null? I assumed that the When expression that I have written would do this, and this part of the validation process would be skipped if source was null however it tries to process the ToString() part of the validation regardless and thus causes an error.

Was it helpful?

Solution

Matches and When are available for the char datatype.

I would suggest something like this...

public class Transaction
{
    public char? source { get; set; }
}


public class CustomerValidator : AbstractValidator<Transaction>
{
    public CustomerValidator()
    {
        RuleFor(t => t.source)
            .Must(IsValidSource);
    }


    private bool IsValidSource(char? source)
    {
        if (source == 'I' || source == 'M' || source == null)
            return true;
        return false;                    
    }
}

OTHER TIPS

I do not know whole context but I see one most obvious solution here:

RuleFor(transaction => transaction.source != null ? transaction.source.ToString() : string.Empty)
    .Matches("^[IM]?$")
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top