Skip to content

Latest commit

 

History

History
81 lines (64 loc) · 3.05 KB

File metadata and controls

81 lines (64 loc) · 3.05 KB

PosInformatique.Foundations.EmailAddresses.FluentValidation

NuGet version NuGet downloads

Introduction

This package provides a FluentValidation extension for validating email addresses using the EmailAddress value object.

It ensures that only valid RFC 5322 compliant email addresses are accepted when validating string properties.

Install

You can install the package from NuGet:

dotnet add package PosInformatique.Foundations.EmailAddresses.FluentValidation

This package depends on the base package PosInformatique.Foundations.EmailAddresses.

Features

  • FluentValidation extension for email address validation
  • Uses the same parsing and validation rules as the EmailAddress value object
  • Clear and consistent error messages

null values are accepted (combine with NotNull() validator to forbid nulls)

Usage

Basic validation

using FluentValidation;

public class User
{
    public string Email { get; set; }
}

public class UserValidator : AbstractValidator<User>
{
    public UserValidator()
    {
        RuleFor(u => u.Email).MustBeEmailAddress();
    }
}

Null values are ignored

var validator = new UserValidator();

// Valid, because null is ignored
var result1 = validator.Validate(new User { Email = null });
Console.WriteLine(result1.IsValid); // True

// Valid, because it's a valid email
var result2 = validator.Validate(new User { Email = "alice@company.com" });
Console.WriteLine(result2.IsValid); // True

// Invalid, because it's not a valid email
var result3 = validator.Validate(new User { Email = "not-an-email" });
Console.WriteLine(result3.IsValid); // False

Require non-null values

public class UserValidator : AbstractValidator<User>
{
    public UserValidator()
    {
        RuleFor(u => u.Email)
            .NotEmpty()             // Disallow null and empty
            .MustBeEmailAddress();
    }
}

Links