Skip to content

agero-core/validator

Repository files navigation

Validator

NuGet Version NuGet Downloads

Model validation library for .NET applications.

Usage:

Define model classes with properties and methods having validation attributes (e.g.,IntValidate) with constraints (e.g.,MinValue) according to your use case. An introductory example is shown below. For additional usage information refer to QuickStartTests.

public class MyClass
{
    [IntValidate("Id must be greater than 0.", MinValue = 1)]
    public int Id { get; set; }

    [StringValidate("Text must have length between 2 and 100 characters.", MinLength = 2, MaxLength = 100)]
    public string Text { get; set; }

    [ComplexTypeValidate] // This attribute tells ValidationHelper to validate MyValueClass object
    [NotNullValidate("MyValue must be specified.")]
    public MyValueClass MyValue { get; set; }

    [ValidateMethod] // This attribute tells ValidationHelper to execute this method as part of model validation
    internal ValidationError ValidateTextHasOnlyLetters()
    {
        if (string.IsNullOrWhiteSpace(Text))
            return null;
        
        if (Text.All(char.IsLetter))
            return null;
        
        return new ValidationError(nameof(Text), "Text must have only letters.");
    }
}

public class MyValueClass
{
    [NotNullValidate("Value must be specified.")]
    public object Value { get; set; }
}

Create an instance of MyClass.

var myClass =
    new MyClass
    {
        Id = -1, // Invalid
        Text = "SomeText", // Valid
        MyValue = // Valid
            new MyValueClass
            {
                Value = null // Invalid
            }
    };

Then use IValidationHelper, which provides three type of methods to validate the object.

// Instantiate ValidationHelper
var validator = new ValidationHelper();

// Validate using one of the following method
var validationErrors = validator.Validate(myClass);

var isMyClassValid = validator.IsValid(myClass);

validator.CheckIsValid(myClass);

About

Model validation library for .NET applications

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages