PropertyValidator 1.0.3

There is a newer version of this package available.
See the version list below for details.
dotnet add package PropertyValidator --version 1.0.3
NuGet\Install-Package PropertyValidator -Version 1.0.3
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="PropertyValidator" Version="1.0.3" />
For projects that support PackageReference, copy this XML node into the project file to reference the package.
paket add PropertyValidator --version 1.0.3
#r "nuget: PropertyValidator, 1.0.3"
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
// Install PropertyValidator as a Cake Addin
#addin nuget:?package=PropertyValidator&version=1.0.3

// Install PropertyValidator as a Cake Tool
#tool nuget:?package=PropertyValidator&version=1.0.3

A simple library to help you validate properties of classes that implements INotifyPropertyChanged.

Service interface

The interface is pretty simple and self-documenting:

public interface IValidationService
{
    RuleCollection<TNotifiableModel> For<TNotifiableModel>(TNotifiableModel notifiableModel) where TNotifiableModel : INotifyPropertyChanged;
    string GetErrorMessage<TNotifiableModel>(TNotifiableModel notifiableModel, Expression<Func<TNotifiableModel, object>> expression) where TNotifiableModel : INotifyPropertyChanged;
    bool Validate();
    event EventHandler<ValidationResultArgs> PropertyInvalid;
}

Usage:

  1. Create the validation rule models by extending the ValidationRule<T> or MultiValidationRule<T>, where T is the type of the target property.
// For email address
public class EmailFormatRule : ValidationRule<string>
{
    public override string ErrorMessage => "Not a valid email format";

    public override bool IsValid(string value)
    {
        if (string.IsNullOrEmpty(value))
            return false;

        const string pattern = @"^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$";
        var regex = new Regex(pattern, RegexOptions.IgnoreCase);
        return regex.IsMatch(value);
    }
}

// For required field
public class RequiredRule : ValidationRule<string>
{
    public override string ErrorMessage => "Izz required!";

    public override bool IsValid(string value)
    {
        return !string.IsNullOrEmpty(value);
    }
}

// If you want to limit the string to a certain length
public class LengthRule : ValidationRule<string>
{
    public override string ErrorMessage => string.Format(Strings.MaxCharacters, max);

    private readonly int max;

    public LengthRule(int max)
    {
        this.max = max;
    }

    public override bool IsValid(string value)
    {
        if (string.IsNullOrEmpty(value))
            return true;

        return value.Length < max;
    }
}

// A multi-property validation model. You can also reuse other ValidationRules here!
public class AddressRule : MultiValidationRule<Address>
{
    protected override RuleCollection<Address> ConfigureRules(RuleCollection<Address> ruleCollection)
    {
        return ruleCollection
            .AddRule(e => e.City, new RequiredRule())
            .AddRule(e => e.CountryIsoCode, new CountryIsoCodeRule())
            .AddRule(e => e.PostalCode, new PostalCodeRule())
            .AddRule(e => e.StreetAddress, new RequiredRule(), new LengthRule(100));
    }
}
  1. Use the validation rules in our classes that implements (implicitly from the base class) INotifyPropertyChanged. The example below is used in Xamarin Forms along with the Prism library to register the service in the Dependency Injection library, but it can be used also in other .NET supported platforms.
public class ItemsPageViewModel : BaseViewModel, IInitialize
{
    private readonly IValidationService validationService;

    public ItemsPageViewModel(INavigationService navigationService, IValidationService validationService) : base(navigationService)
    {
        this.validationService = validationService;
    }

    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string EmailAddress { get; set; }
    public Address PhysicalAddress { get; set; } = new Address();

    public string FirstNameError { get; set; }
    public string LastNameError { get; set; }
    public string EmailAddressError { get; set; }
    public string PhysicalAddressError { get; set; }

    // You must do this only once in the initialization part of your class model.
    public void Initialize(INavigationParameters parameters)
    {
        validationService.For(this)
            .AddRule(e => e.FirstName, new RequiredRule())
            .AddRule(e => e.LastName, new LengthRule(50))
            .AddRule(e => e.EmailAddress, new RequiredRule(), new LengthRule(100), new EmailFormatRule())
            // The error message have been overriden to "Deez nuts" since an aggregated error messages is awful.
            .AddRule(e => e.PhysicalAddress, "Deez nuts", new AddressRule()); 

        validationService.PropertyInvalid += ValidationService_PropertyInvalid;
    }

    private void ValidationService_PropertyInvalid(object sender, ValidationResultArgs e)
    {
        switch (e.PropertyName)
        {
            case nameof(FirstName):
                FirstNameError = e.FirstError;
                break;
            case nameof(LastName):
                LastNameError = e.FirstError;
                break;
            case nameof(EmailAddress):
                EmailAddressError = e.FirstError;
                break;
            case nameof(PhysicalAddress):
                PhysicalAddressError = e.FirstError;
                break;
        }
        // To retrieve all the error message of the property, use:
        var errorMessages = e.ErrorMessages;
    }
}
  1. If you wish not to use PropertyInvalid event to check every time the property have changed, you can also invoke manually the IValidationService.Validate(), check the return, if it's false, find the error message using IValidationService.GetErrorMessage(...)
private void ShowValidationResult()
{
    ErrorFirstName = validationService.GetErrorMessage(this, e => e.FirstName);
    ErrorLastName = validationService.GetErrorMessage(this, e => e.LastName);
    ErrorEmailAddress = validationService.GetErrorMessage(this, e => e.EmailAddress);
    PhysicalAddressError = validationService.GetErrorMessage(this, e => e.PhysicalAddress);
}

private void Register()
{
    if (!validationService.Validate())
    {
        ShowValidationResult();
        return;
    }

    ...
}	

Result

Xamarin.Android

Support

Feel free to contribute if you find some issues or you have more ideas to add 😃

Product Compatible and additional computed target framework versions.
.NET net5.0 was computed.  net5.0-windows was computed.  net6.0 was computed.  net6.0-android was computed.  net6.0-ios was computed.  net6.0-maccatalyst was computed.  net6.0-macos was computed.  net6.0-tvos was computed.  net6.0-windows was computed.  net7.0 was computed.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 was computed.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed. 
.NET Core netcoreapp2.0 was computed.  netcoreapp2.1 was computed.  netcoreapp2.2 was computed.  netcoreapp3.0 was computed.  netcoreapp3.1 was computed. 
.NET Standard netstandard2.0 is compatible.  netstandard2.1 was computed. 
.NET Framework net461 was computed.  net462 was computed.  net463 was computed.  net47 was computed.  net471 was computed.  net472 was computed.  net48 was computed.  net481 was computed. 
MonoAndroid monoandroid was computed. 
MonoMac monomac was computed. 
MonoTouch monotouch was computed. 
Tizen tizen40 was computed.  tizen60 was computed. 
Xamarin.iOS xamarinios was computed. 
Xamarin.Mac xamarinmac was computed. 
Xamarin.TVOS xamarintvos was computed. 
Xamarin.WatchOS xamarinwatchos was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.
  • .NETStandard 2.0

    • No dependencies.

NuGet packages (1)

Showing the top 1 NuGet packages that depend on PropertyValidator:

Package Downloads
PropertyValidator.ValidationPack

Contains common validation rules for PropertyValidator

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last updated
1.1.1 456 12/25/2023
1.1.0.1 379 12/18/2023
1.1.0 500 9/19/2023
1.0.6.7 835 5/9/2021
1.0.6.6 844 5/9/2021
1.0.6.5 847 5/9/2021
1.0.6.4 812 4/10/2021
1.0.6.3 833 4/10/2021
1.0.6.2 817 4/10/2021
1.0.6.1 852 4/10/2021
1.0.6 923 11/1/2020
1.0.4 991 10/31/2020
1.0.4-patch 883 10/31/2020
1.0.3 920 9/23/2020
1.0.1 981 9/5/2020

Added support for multi-property validation.