Skip to content

aliastopan/AnnotatedResult

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

AnnotatedResult

Nuget Nuget Nuget Nuget GitHub

AnnotatedResult is a lightweight .NET model validation library utilizing System.ComponentModel.DataAnnotations.

NuGet Package

dotnet add package AnnotatedResult --version 1.0.0-rc.4
dotnet add package AnnotatedResult.AspNetCore --version 1.0.0-rc.4

Overview

Validation

public class Request
{
    [Required]
    [RegularExpression(RegexPattern.Username)]
    public string Username { get; init; }

    [EmailAddress]
    public string Email { get; init; }

    [Required]
    [RegularExpression(RegexPattern.StrongPassword)]
    public string Password { get; init; }
}

Request is a class with Data Annotation attribute assigned for each properties. AnnotatedResult make it so it's easy to validate.

    var request = new Request();
    bool isValid = request.TryValidate(out Error[] errors);

TryValidate is an extension method use to validation any instance of object. If the object has Data Annotation attribute assigned to either field of property it will perform the validation process and return a boolean and an out parameter of type Error[].

    if(!isValid)
    {
        Result<Request> result = Result<Request>.Invalid(errors);
        return result;
    }

    Result<Request> result = Result<Request>.Ok(request);
    return result;

Result<T> is a generic wrapper class that encapsulate Data Annotation validation result. The example above it hold the generic type of Request. Result<T> can be modified whether the is a success or an error--or a specified error such as Unauthorized or NotFound.

Result<T> with 200 status code or Ok status return the validated object in question where as error (specified or otherwise) return list of errors.

    var ok           = Result<Request>.Ok(request);

    var error        = Result<Request>.Error(errors);
    var invalid      = Result<Request>.Invalid(errors);
    var unauthorized = Result<Request>.Unauthorized(errors);
    var forbidden    = Result<Request>.Forbidden(errors);
    var conflict     = Result<Request>.Conflict(errors);
    var notFound     = Result<Request>.NotFound(errors);

About

A result abstraction with built-in validation using Data Annotation.

Resources

License

Stars

Watchers

Forks

Languages