简体   繁体   中英

FluentValidation not working for a null property

I'm using FluentValidation with IDataErrorInfo , and I have a validator defined as follows:

public class StsInfoValidator : AbstractValidator<StsInfo>
{
    public StsInfoValidator()
    {
        RuleFor(x => x.SomeProperty).Cascade(CascadeMode.StopOnFirstFailure)
            .NotNull().NotEmpty().WithMessage("SomeProperty is required.");

    }        
}

However, passing in a null property doesn't seem to trigger the validator:

#region IDataErrorInfo

public string this[string columnName]
{
    get
    {

        var validator = new StsInfoValidator();

        if (columnName.Equals("SomeProperty"))
        {
            // SomeProperty below is null
            if (validator.Validate(this, SomeProperty).Errors.Any())
                return validator.Validate(this, CampusNexusApiServer).Errors.FirstOrDefault().ErrorMessage;
            else
            {
                validator = null;
                return string.Empty;
            }
        }

        return string.Empty;
    }
}

#endregion

The problem you have is that if you choose to use the Validate overload that requires a lambda expression to evaluate your property you'll have to do:

Instead of:

validator.Validate(this, SomeProperty);

you need:

validator.Validate(this, s => s.SomeProperty);

Here this overload documentation:

在此处输入图片说明

Alternatively you can use the other Validate overload and pass the name of your property as a string:

validator.Validate(this, columnName); or validator.Validate(this, "SomeProperty");

Here is the property Name(s) overload for Validate:

在此处输入图片说明

    public string this[string columnName]
    {
        get
        {

            var validator = new StsInfoValidator();

            if (columnName.Equals("SomeProperty"))
            {
                // SomeProperty below is null
                //option 1
                var result  = validator.Validate(this,s => s.SomeProperty);
                //option 2
                //var result  = validator.Validate(this, columnName);
                //option 3
                //var result  = validator.Validate(this, "SomeProperty");
                if (result.Errors.Any())
                    return validator.Validate(this, CampusNexusApiServer).Errors.FirstOrDefault().ErrorMessage;
                else
                {
                    validator = null;
                    return string.Empty;
                }
            }

            return string.Empty;
        }
    }

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM