PropertyValidator is a versatile library designed to simplify property validation for classes that implement the INotifyPropertyChanged
interface. It offers a straightforward way to define and apply validation rules to properties, making it easier to ensure the integrity of your data.
You can install the PropertyValidator library via NuGet:
Install-Package PropertyValidator
using PropertyValidator;
class ViewModel : INotifyPropertyChanged, INotifiableModel
{
// We are just converting the function to readonly property. This will be accessed by XAML later.
public IDictionary<string, string?> Errors => validationService.GetErrors();
// Implement INotifiableModel so it propagates changes to XAML
public void NotifyErrorPropertyChanged() => RaisePropertyChanged(nameof(Errors));
// I have only included this here for clarity. Substitute with your own implentation.
private void RaisePropertyChanged([CallerMemberName] string? propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
var validationService = new ValidationService();
// Register your INPC instance for validation
validationService.For(this, delay: TimeSpan.FromSeconds(0.7))
.AddRule(e => e.FirstName, new StringRequiredRule(), new MinLengthRule(2))
.AddRule(e => e.LastName, new StringRequiredRule(), new MaxLengthRule(5))
.AddRule(e => e.EmailAddress, new StringRequiredRule(), new EmailFormatRule(), new RangeLengthRule(10, 15))
<Entry
Text="{Binding EmailAddress}"
Keyboard="Email"
Placeholder="Email address" />
<Label
Text="{Binding Errors[EmailAddress]}"
TextColor="Red"
FontSize="Small" />
...
PropertyValidator offers a range of features to streamline your validation process:
- Simple and intuitive API for defining validation rules.
- Supports both single-property rules and multi-property rules.
- Allows you to create custom and simple to create validation rules.
- Provides options to manually trigger validation or automatically ensure properties are valid.
- Offers event-based error handling through the
PropertyInvalid
event. - Supports delayed validation to enhance user experience.
- Format error messages using
SetErrorFormatter(errorMessages => ...)
.
ValidationPack contains a set of common validation rules to cover popular input validation scenarios. The ValidationPack includes the following rules:
- StringRequiredRule: Ensures that a string property is not empty or null.
- MaxLengthRule: Validates that a string does not exceed a specified maximum length.
- MinLengthRule: Checks that a string meets a specified minimum length.
- RangeLengthRule: Validates that a string falls within a specific length range.
- EmailFormatRule: Ensures that a string follows a valid email format.
PropertyValidator allows you to create custom validation rules to suit your specific validation requirements. To create a custom validation rule, follow these steps:
-
Create a new class that inherits from
ValidationRule<T>
, whereT
is the type of the property you want to validate. -
Implement the
IsValid(T value)
method in your custom rule class. This method should returntrue
if the value is valid according to your rule, andfalse
otherwise. -
Override the
ErrorMessage
property to provide a custom error message that will be displayed when the validation fails.
Here's an example of creating a custom validation rule to check if a string contains only alphanumeric characters:
using PropertyValidator;
public class AlphanumericRule : ValidationRule<string>
{
public override string ErrorMessage => "Only alphanumeric characters are allowed.";
public override bool IsValid(string value)
{
if (string.IsNullOrEmpty(value))
return true;
// Use regular expression to check if the string contains only alphanumeric characters
const string pattern = "^[a-zA-Z0-9]*$";
return Regex.IsMatch(value, pattern);
}
}
Now, you can use your custom validation rule in your validation service. Here's an example of how to use the AlphanumericRule
:
var validationService = new ValidationService();
// Register your model for validation and include the custom rule
validationService.For(this)
.AddRule(e => e.Username, new AlphanumericRule());
Feel free to contribute to the project, report issues, or provide feedback to help us improve PropertyValidator
.