Skip to the content.

Kitpymes.Core.Validations

Validaciones para multiples proveedores

Build Status NuGet Status NuGet Download License Size Repo Last Commit

📋 Requerimientos

🔧 Instalación

Se puede instalar usando el administrador de paquetes Nuget o CLI dotnet.

Nuget

Install-Package Kitpymes.Core.Validations

CLI dotnet

dotnet add package Kitpymes.Core.Validations

⌨️ Código

public class ValidationsException : Exception
{
    public ValidationsException(params string[] messages) {}

    public ValidationsException(IDictionary<string, string> messages) {}

    public int? Count { get; }

    public bool Contains(string message) {}
}

Validator

public static class Validator
{
    public static ValidatorRule AddRule(object? value, Action<ValidatorRuleOptions> options) {}

    public static ValidatorRule AddRule(Func<bool> condition, string message) {}
}
public class ValidatorRule
{
    public bool IsValid { get; }

    public static void Add(Func<string> rule)  {}

    public ValidatorRule StopFirstError(bool stopFirstError = true) {}

    public ValidatorRule AddRule(object? value, Action<ValidatorRuleOptions> options) {}

    public ValidatorRule AddRule(Func<bool> condition, string message) {}

    public void Throw() {}

    public async Task ThrowAsync() {}

    public void ThrowApplicationException() {}

    public async Task ThrowApplicationExceptionAsync() {}
}
public class ValidatorRuleOptions
{
    public ValidatorRuleOptions IsNullOrAny(string? overrideRureFieldName = null) {}

    public ValidatorRuleOptions IsNullOrAnyWithMessage(string message) {}

    public ValidatorRuleOptions IsEqual(IEnumerable? valueCompare, (string fieldName, string fieldNameCompare)? fieldsName = null) {}

    public ValidatorRuleOptions IsEqualWithMessage(IEnumerable? valueCompare, string message) {}

    public ValidatorRuleOptions IsGreater(long max, string? overrideRureFieldName = null) {}

    public ValidatorRuleOptions IsGreaterWithMessage(long max, string message) {}

    public ValidatorRuleOptions IsLess(long min, string? overrideRureFieldName = null) {}

    public ValidatorRuleOptions IsLessWithMessage(long min, string message) {}

    public ValidatorRuleOptions IsNullOrEmpty(string? overrideRureFieldName = null) {}

    public ValidatorRuleOptions IsNullOrEmptyWithMessage(string message) {}

    public ValidatorRuleOptions IsRange(long min, long max, string? overrideRureFieldName = null) {}

    public ValidatorRuleOptions IsRangeWithMessage(long min, long max, string message) {}

    public ValidatorRuleOptions IsRegex(string regex, string? overrideRureFieldName = null) {}

    public ValidatorRuleOptions IsRegexWithMessage(string regex, string message) {}

    public ValidatorRuleOptions IsDirectory(string? overrideRureFieldName = null) {}

    public ValidatorRuleOptions IsDirectoryWithMessage(string message) {}

    public ValidatorRuleOptions IsEmail(string? overrideRureFieldName = null) {}

    public ValidatorRuleOptions IsEmailWithMessage(string message) {}

    public ValidatorRuleOptions IsFileExtension(string? overrideRureFieldName = null) {}

    public ValidatorRuleOptions IsFileExtensionWithMessage(string message) {}

    public ValidatorRuleOptions IsFile(string? overrideRureFieldName = null) {}

    public ValidatorRuleOptions IsFileWithMessage(string message) {}

    public ValidatorRuleOptions IsName(string? overrideRureFieldName = null) {}

    public ValidatorRuleOptions IsNameWithMessage(string message) {}

    public ValidatorRuleOptions IsPassword(long min, string? overrideRureFieldName = null) {}

    public ValidatorRuleOptions IsPasswordWithMessage(long min, string message) {}

    public ValidatorRuleOptions IsSubdomain(string? overrideRureFieldName = null) {}

    public ValidatorRuleOptions IsSubdomainWithMessage(string message) {}
}

Ejemplo

using Kitpymes.Core.Validations;
using System;

public class Person
{
    public Person(int age, string name, string email)
    {
        Validator
            .AddRule(age, x => x.IsLess(17).IsGreater(51).WithRuleFieldName("Edad"))
            .AddRule(name, x => x.IsName("Nombre"))
            .AddRule(email, x => x.IsEmailWithMessage("El correo eléctronico tiene un formato incorrecto."))
            .Throw();

        Id = Guid.NewGuid();
        Age = age;
        Name = name;
        Email = email;
    }

    public Person ChangeName(string name)
    {
        Validator.AddRule(name, x => x.IsName("Nombre")).Throw();

        Name = name;

        return this;
    }

    public Guid Id { get; private set; }
    public int Age { get; private set; }
    public string? Name { get; private set; }
    public string? Email { get; private set; }
}

FluentValidation

Agregamos el middlware en la clase Startup

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    app.LoadValidations();
}

Opción 1: configuración desde el appsetings

{
    "ValidationsSettings": {
        "Enabled": true, // Default: false
        "FluentValidationSettings": {
            "Enabled": true, // Default: false
            "Assemblies": [ "Api.Models" ] // Default: null
        }
    }
}
public void ConfigureServices(IServiceCollection services)
{
    services.LoadValidations(Configuration);
}

Opción 2: configuración manual, agregamos los assemblies en formato string

public void ConfigureServices(IServiceCollection services)
{
    services.LoadValidations(validator => validator.WithEnabled().WithFluentValidation("App.Models"));
}

Ejemplo

public class PersonAddDto 
{
    public int? Age { get; set; }
    public string? Name { get; set; }
    public string? Email { get; set; }
}
using FluentValidation;
using Kitpymes.Core.Validations.FluentValidation;

public class PersonAddDtoValidator : AbstractValidator<PersonAddDto>
{
    public PersonAddDtoValidator()
    {
        RuleFor(_ => _.Age).IsRange(17, 51, "Edad");
        RuleFor(_ => _.Name).IsName("Nombre").IsLess(100);
        RuleFor(_ => _.Email).IsEmailWithMessage("El correo eléctronico tiene un formato incorrecto.");
    }
}

🔩 Resultados ( Solo en modo Development muestra el Details )

Resultado utilizando FluentValidation

Resultado utilizando FluentValidation

Resultado utilizando Validator

Resultado utlizando Validator

⚙️ Pruebas Unitarias

Cada proyecto tiene su test que se ejecutan desde el “Explorador de pruebas”

Resultado pruebas

🛠️ Construido con

✒️ Autores

📄 Licencia

🎁 Gratitud


Kitpymes 😊