I\'ve been trying to work out how to create a FluentValidation rule that checks if the instance of an object it\'s validating is not null, prior to validating it\'s properti
Override EnsureInstanceNotNull as below
protected override void EnsureInstanceNotNull(object instanceToValidate)
{
if(instanceToValidate==null)
throw new ValidationException("Customer can not be null");
}
I can't really test that right now, but you can either try to override Validate
, or include the rules in the When
block:
public CustomerValidator()
{
When(x => x != null, () => {
RuleFor(x => x.Surname).NotEmpty();
//etc.
});
}
By means of Custom(). It can be also very helpful when validation of another field is based on validation of your current field.
ruleBuilder.Custom((obj, context) =>
{
if (obj != null)
{
var propertyName = <field where should be validation>;
context.AddFailure(propertyName, "'Your field name' Your validation message.");
}
});