'Fluent Validation to check just ID property

I am using Fluent Validation in my project.

I have one validator class.

public class CarValidator : AbstractValidator<Car>
{
    public CarValidator()
    {
        RuleFor(p => p.Id).NotEmpty();
        RuleFor(p => p.Name).MinimumLength(2);
        RuleFor(p => p.DailyPrice).GreaterThanOrEqualTo(0);
        RuleFor(p => p.ColorId).NotEmpty();
        RuleFor(p => p.BrandId).NotEmpty();
        RuleFor(p => p.DailyPrice).GreaterThanOrEqualTo(0);
        RuleFor(p => p.ModelYear).GreaterThanOrEqualTo(1950);
        RuleFor(p => p.Name).NotEmpty();
        RuleFor(p => p.Description).NotEmpty().MinimumLength(10);
        
    }
}

Delete method in my controller class

    [ValidationAspect(typeof(CarValidator))]
    public IResult Delete(Car car)
    {
        _carDal.Delete(car);
        return new SuccessResult(Messages.CarDeleted);
    }

POSTMAN Response Body

    FluentValidation.ValidationException: Validation failed: 
 -- Id: 'Id' must not be empty.
 -- ColorId: 'Color Id' must not be empty.
 -- BrandId: 'Brand Id' must not be empty.
 -- ModelYear: 'Model Year' must be greater than or equal to '1950'.
 -- Name: 'Name' must not be empty.
 -- Description: 'Description' must not be empty.

When I make a request to the delete method, all properties are checked. But I just want Id to be checked ?



Solution 1:[1]

You can refer to Validator Customization section in Fluentvalidation documents.

Add a CustomizeValidator attribute before your model with Id property.

public IResult Delete([CustomizeValidator(Properties="Id")] Car car)
{
    _carDal.Delete(car);
    return new SuccessResult(Messages.CarDeleted);
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Bao To Quoc