IRONSOFTWAREHOME
USING IRONPDF

How to Use Fluent Validation With IronPDF in C#

Curtis Chau
Curtis Chau
Updated: April 21, 2026

What is Fluent Validation?

FluentValidation is a .NET validation library that helps in building strongly typed validation rules. It uses a fluent interface and lambda expressions, making the code more readable and maintainable. Instead of using data annotations or manual validation in your model classes, you can use Fluent Validation to build a separate class for your validation logic.

Fluent Validation brings more flexibility to the validation game. With built-in validators for common scenarios, the ability to build custom validations, and a simple way to chain validation rules, Fluent Validation is a powerful tool in the .NET Core toolkit.

Understanding Fluent Validation

Fluent Validation is an open-source library for .NET that makes it easy to build validation rules for your model classes.

  1. Validators: Validators are classes that encapsulate the validation logic. They are typically created by inheriting from the AbstractValidator<T> base class.
  2. Rules: A rule is a validation condition that a property must meet. Rules are defined using the RuleFor method in a validator class.
  3. Validation Failures: If a rule fails, Fluent Validation creates a ValidationFailure object that contains details about the error, including the property name and error message.

What is IronPDF?

IronPDF - Convert HTML to PDF in C# is a powerful .NET library that allows you to generate PDF documents from HTML content. Whether you need to create invoices, reports, or any other type of document, IronPDF provides an easy-to-use solution. It seamlessly integrates with your ASP.NET Core applications, enabling you to generate high-quality PDF files with just a few lines of code.

Using Fluent Validation with IronPDF

Now that we understand what Fluent Validation and IronPDF are, let's see how they can be used together. This tutorial will help build an invoice generator, where the invoice content will be validated using FluentValidation in ASP.NET Core before generating the PDF using IronPDF.

Setting Up the Project

To begin, let's create a new Console Application in Visual Studio or your preferred development environment.

  1. Open Visual Studio and go to File > New > Project.

  2. Select "Console App (ASP.NET Core)" as the project template and provide a name for your project.

    How to Use Fluent Validation With IronPDF in C#, Figure 1: Create a new Console Application Create a new Console Application

  3. Click the Next button and configure your project by naming it and selecting the repository location.

    How to Use Fluent Validation With IronPDF in C#, Figure 2: Configure the new application Configure the new application

  4. Click on the Next button and select the .NET Framework. The latest .NET Framework (7) is recommended.

    How to Use Fluent Validation With IronPDF in C#, Figure 3: .NET Framework selection .NET Framework selection

  5. Click on the Create button to create the project.

Install Required Packages

Once the project is created, add the necessary NuGet packages for Fluent Validation and IronPDF.

  1. Right-click on the project in the Solution Explorer and select "Manage NuGet Packages."

  2. Search for "FluentValidation" and click "Install" to add the package to your project.

    How to Use Fluent Validation With IronPDF in C#, Figure 4: Install the FluentValidation package in NuGet Package Manager UI Install the FluentValidation package in NuGet Package Manager UI

  3. Similarly, search for "IronPDF - Powerful .NET PDF Library" and install the IronPDF package.

Alternatively, you can install IronPDF using NuGet Package Manager Console with the following command:

PM > Install-Package IronPdf

How to Use Fluent Validation With IronPDF in C#, Figure 5: Install the IronPDF package in the Package Manager Console Install the IronPDF package in the Package Manager Console

With the project set up and the required packages installed, let's move on to defining the PDF content class.

Defining the PDF Content

In this example, a simple invoice PDF will be created from the HTML codes in two classes: InvoiceContent and InvoiceItem.

using System.Collections.Generic;
using System.Linq;

public abstract class PdfContent
{
    // Abstract method to generate the HTML string
    public abstract string RenderHtml();
}

public class InvoiceContent : PdfContent
{
    public string CustomerName { get; set; }
    public string Address { get; set; }
    public List<InvoiceItem> InvoiceItems { get; set; }

    // Constructs the HTML representation of the invoice
    public override string RenderHtml()
    {
        string invoiceItemsHtml = string.Join("", InvoiceItems.Select(item => $"<li>{item.Description}: {item.Price}</li>"));
        return $"<h1>Invoice for {CustomerName}</h1><p>{Address}</p><ul>{invoiceItemsHtml}</ul>";
    }
}

public class InvoiceItem
{
    public string Description { get; set; }
    public decimal Price { get; set; }
}

In the code above, an abstract PdfContent class is defined with an abstract method called RenderHtml. The InvoiceContent class extends PdfContent and represents the content of the invoice PDF. It has properties for the customer's name, address, and a list of invoice items. The InvoiceItem class contains two properties: 'Description' and 'Price'. The RenderHtml method generates the HTML markup for the invoice based on the content.

Now that the PDF content is defined, let's move on to creating validation rules using Fluent Validation.

Creating Validation Rules

For building validation rules for the InvoiceContent class, create a validator class called InvoiceContentValidator. This class will inherit from AbstractValidator<InvoiceContent>, which is provided by FluentValidation.

using FluentValidation;

public class InvoiceContentValidator : AbstractValidator<InvoiceContent>
{
    public InvoiceContentValidator()
    {
        RuleFor(content => content.CustomerName).NotEmpty().WithMessage("Customer name is required.");
        RuleFor(content => content.Address).NotEmpty().WithMessage("Address is required.");
        RuleFor(content => content.InvoiceItems).NotEmpty().WithMessage("At least one invoice item is required.");
        RuleForEach(content => content.InvoiceItems).SetValidator(new InvoiceItemValidator());
    }
}

public class InvoiceItemValidator : AbstractValidator<InvoiceItem>
{
    public InvoiceItemValidator()
    {
        RuleFor(item => item.Description).NotEmpty().WithMessage("Description is required.");
        RuleFor(item => item.Price).GreaterThanOrEqualTo(0).WithMessage("Price must be greater than or equal to 0.");
    }
}

In the source code, the InvoiceContentValidator class is defined, which inherits from AbstractValidator<InvoiceContent>. Inside the constructor of the validator class, the RuleFor method defines validation rules for each property of the InvoiceContent class.

For example, RuleFor(content => content.CustomerName) specifies that the customer name should not be empty. Similarly, validation rules are defined for the address and invoice items properties.

The RuleForEach method iterates over each item in the InvoiceItems list and applies the InvoiceItemValidator. The InvoiceItemValidator class contains validation rules for the InvoiceItem class.

With these validation rules in place, let's move on to generating the PDF using IronPDF.

Generating PDF using IronPDF

IronPDF - Generate and Edit PDF Documents is a popular .NET library for creating and manipulating PDF documents. IronPDF will be used to generate the PDF based on the validated invoice content.

using IronPdf;
using FluentValidation;

public class PdfService
{
    // Generates a PDF document for the provided content
    public PdfDocument GeneratePdf<T>(T content) where T : PdfContent
    {
        // Validate the content using the appropriate validator
        var validator = GetValidatorForContent(content);
        var validationResult = validator.Validate(content);

        // Check if validation is successful
        if (!validationResult.IsValid)
        {
            throw new FluentValidation.ValidationException(validationResult.Errors);
        }

        // Generate the PDF using IronPDF
        var renderer = new ChromePdfRenderer();
        return renderer.RenderHtmlAsPdf(content.RenderHtml());
    }

    // Retrieves the appropriate validator for the content
    private IValidator<T> GetValidatorForContent<T>(T content) where T : PdfContent
    {
        if (content is InvoiceContent)
        {
            return (IValidator<T>)new InvoiceContentValidator();
        }
        else
        {
            throw new NotSupportedException("Unsupported content type.");
        }
    }
}

The PdfService class provides a GeneratePdf method. This method takes a PdfContent object as input and generates the PDF document based on the validated content.

First, it retrieves the appropriate validator for the content by calling the GetValidatorForContent method, which checks the type of content and returns the corresponding validator. In our case, we support InvoiceContent and use the InvoiceContentValidator.

Next, the content is validated using the validator by calling its Validate method. The validation result is stored in a ValidationResult object.

If the validation fails (!validationResult.IsValid), a FluentValidation.ValidationException is thrown with the validation errors. Otherwise, the PDF is generated using IronPDF.

An instance of ChromePdfRenderer is created to render the HTML content as a PDF. The RenderHtmlAsPdf method is called on the renderer object, passing in the HTML generated by the content.RenderHtml method, generating the PDF document.

Now that we have defined the PDF generation logic, let's handle any validation errors that may occur.

Handling Validation Errors

When a validation error occurs, we want to display an error message and handle it gracefully. Let's modify the Main method of the Program class to handle any exceptions and display meaningful messages to the user.

using System;
using System.Collections.Generic;

public class Program
{
    static void Main(string[] args)
    {
        var pdfService = new PdfService();

        // Test 1: Empty Customer Name
        try
        {
            var invoiceContent = new InvoiceContent
            {
                CustomerName = "",
                Address = "123 Main St, Anytown, USA",
                InvoiceItems = new List<InvoiceItem> {
                    new InvoiceItem { Description = "Item 1", Price = 19.99M },
                    new InvoiceItem { Description = "Item 2", Price = 29.99M }
                }
            };

            var pdfDocument = pdfService.GeneratePdf(invoiceContent);
            pdfDocument.SaveAs("C:\\TestInvoice.pdf");
            Console.WriteLine("PDF generated successfully!");
        }
        catch (Exception ex)
        {
            Console.WriteLine("Error generating PDF: " + ex.Message);
        }

        // Test 2: Empty InvoiceItems
        try
        {
            var invoiceContent = new InvoiceContent
            {
                CustomerName = "John Doe",
                Address = "123 Main St, Anytown, USA",
                InvoiceItems = new List<InvoiceItem>()  // Empty list
            };

            var pdfDocument = pdfService.GeneratePdf(invoiceContent);
            pdfDocument.SaveAs("C:\\TestInvoice.pdf");
            Console.WriteLine("PDF generated successfully!");
        }
        catch (Exception ex)
        {
            Console.WriteLine("Error generating PDF: " + ex.Message);
        }

        // Successful generation
        try
        {
            var invoiceContent = new InvoiceContent
            {
                CustomerName = "John Doe",
                Address = "123 Main St, Anytown, USA",
                InvoiceItems = new List<InvoiceItem> {
                    new InvoiceItem { Description = "Item 1", Price = 19.99M },
                    new InvoiceItem { Description = "Item 2", Price = 29.99M }
                }
            };
            var pdfDocument = pdfService.GeneratePdf(invoiceContent);
            pdfDocument.SaveAs("C:\\TestInvoice.pdf");
            Console.WriteLine("PDF generated successfully!");
        }
        catch (Exception ex)
        {
            Console.WriteLine("Error generating PDF: " + ex.Message);
        }
    }
}

In the code above, try-catch blocks are used to catch any exceptions that may occur. If an exception is caught, an error message will be shown to the user using Console.WriteLine.

Now let's test this application with different scenarios to validate the PDF generation and the validation rules.

Testing the Application

In the code example, there are three scenarios to test:

  1. Empty customer name: Leave the customer name empty to trigger a validation error.
  2. Empty invoice items: Provide an empty list of invoice items to trigger a validation error.
  3. Successful generation: Provide valid content to generate the PDF successfully.

Run the application and observe the output in the console.

Error generating PDF: Validation failed:
    -- CustomerName: Customer name is required. Severity: Error
Error generating PDF: Validation failed:
    -- InvoiceItems: At least one invoice item is required. Severity: Error
PDF generated successfully!
Text

How to Use Fluent Validation With IronPDF in C#, Figure 6: The output error in the Console The output error in the Console

How to Use Fluent Validation With IronPDF in C#, Figure 7: The output PDF file The output PDF file

As expected, validation errors are shown for the first two scenarios and a success message for the third scenario.

Conclusion

This tutorial explored Fluent Validation and how to use it with IronPDF to generate PDF documents. Starting by setting up a Console Application and defining the PDF content class. Then, created validation rules using Fluent Validation and tested the PDF generation with different scenarios.

Fluent Validation provides a flexible and easy-to-use approach for validating objects in .NET applications. It allows you to define validation rules in a strongly typed manner, customize error messages, and handle validation errors gracefully.

IronPDF Free Trial & Licensing Information offers a free trial, and the license starts from $499 per developer.

Curtis Chau
Technical Writer

Curtis Chau holds a Bachelor’s degree in Computer Science (Carleton University) and specializes in front-end development with expertise in Node.js, TypeScript, JavaScript, and React. Passionate about crafting intuitive and aesthetically pleasing user interfaces, Curtis enjoys working with modern frameworks and creating well-structured, visually appealing manuals.

...
Read More

Related Articles

Key in blue circle

Get your free 30-day Trial Key instantly.

Your trial license will be sent to your email address

No limitations. 100% unlocked. No credit card.

OR
bullet_checkedNo credit card or account creation requiredNo limitations. 100% unlocked. No credit card.
  • Logo Aetna
  • Logo NASA
  • Logo GE
  • Logo Porsche
  • Logo USDA
  • Logo Qatar
Join Millions of Engineers who’ve tried Iron Suite
Book your free Live Demo
Booking Badge

Trusted by Millions of Engineers Worldwide

Iron Software's customer logos
Get Your No-Obligation Consult
Complete the form below or email sales@ironsoftware.com
Your details will always be kept confidential.
Trusted by Millions of Engineers Worldwide
Iron Software's customer logos
Get your free 30-day Trial Key instantly.
No credit card or account creation required
C# NuGet Library for PDF
Install with NuGet

Version: 2026.9

PM > Install-Package IronPdf
nuget.org/packages/IronPdf/
  1. In Solution Explorer, right-click References, Manage NuGet Packages
  2. Select Browse and search "IronPdf"
  3. Select the package and install
C# PDF DLL
Download DLL

Version: 2026.9

or download Windows Installer here.

  1. Download and unzip IronPDF to a location such as ~/Libs within your Solution directory
  2. In Visual Studio Solution Explorer, right click References. Select Browse, "IronPdf.dll"

Licenses from $999