All Projects → ryanelian → Fluentvalidation.blazor

ryanelian / Fluentvalidation.blazor

Licence: mit
Fluent Validation-powered Blazor component for validating standard <EditForm> 🌌 ✅

Projects that are alternatives of or similar to Fluentvalidation.blazor

linqjs
use linq and lambda in javascript on es6, can use linq function in an Object or an Array or a String value | 一个方便对数组、字典、树形数据进行操作、筛选等操作的工具库
Stars: ✭ 17 (-87.86%)
Mutual labels:  linq, lambda
Quicklib
Quick development library (AutoMapper, LinQ, IOC Dependency Injection, MemoryCache, Scheduled tasks, Config, Serializers, etc) with crossplatform support for Delphi/Firemonkey (Windows,Linux,OSX/IOS/Android) and freepascal (Windows/Linux).
Stars: ✭ 274 (+95.71%)
Mutual labels:  linq, dependency-injection
granitic
Web/micro-services and IoC framework for Golang developers
Stars: ✭ 32 (-77.14%)
Mutual labels:  validation, dependency-injection
Uragano
Uragano, A simple, high performance RPC library. Support load balancing, circuit breaker, fallback, caching, intercepting.
Stars: ✭ 28 (-80%)
Mutual labels:  dependency-injection, asp-net-core
Daggraph
Dagger dependency graph generator for Android Developers
Stars: ✭ 1,140 (+714.29%)
Mutual labels:  dependency-injection, component
Asmin
Asmin is .NET CORE project infrastructure, to get a quick start on the project.
Stars: ✭ 89 (-36.43%)
Mutual labels:  dependency-injection, asp-net-core
netcore-wcf-service-proxy
Example of consuming multiple WCF services using a proxy implementation in a ASP.NET Core Web-application.
Stars: ✭ 42 (-70%)
Mutual labels:  dependency-injection, asp-net-core
Masuit.tools
ldqk.xyz/55
Stars: ✭ 2,539 (+1713.57%)
Mutual labels:  lambda, linq
Vue.js With Asp.net Core Sample
This provides a sample code using vue.js running on ASP.NET Core
Stars: ✭ 44 (-68.57%)
Mutual labels:  asp-net-core, dependency-injection
Professionalcsharp7
Code samples for the book Professional C# 7 and .NET Core 2.0 (with updates for 2.1), Wrox Press
Stars: ✭ 403 (+187.86%)
Mutual labels:  asp-net-core, dependency-injection
Inyector
Library to Implement Automatic dependency injection by Configuration over Scaned Assemblies
Stars: ✭ 13 (-90.71%)
Mutual labels:  dependency-injection, asp-net-core
Scrutor
Assembly scanning and decoration extensions for Microsoft.Extensions.DependencyInjection
Stars: ✭ 1,915 (+1267.86%)
Mutual labels:  asp-net-core, dependency-injection
Dapper.lnskydb
基于Dapper的LINQ扩展,支持Lambda表达式,支持按时间分库分表,也可以自定义分库分表方法,且实体类有T4模版自动生成.省去手写实体类的麻烦。已在实际项目使用
Stars: ✭ 228 (+62.86%)
Mutual labels:  lambda, linq
lambda2js
Converts a C# expression tree (from Linq namespace) to a syntatically correct javascript code.
Stars: ✭ 51 (-63.57%)
Mutual labels:  linq, lambda
Jaque
Lets Java 8 Lambdas to be represented as objects in the form of expression trees at runtime
Stars: ✭ 152 (+8.57%)
Mutual labels:  lambda, linq
SocketHook
Socket hook is an injector based on EasyHook (win only) which redirect the traffic to your local server.
Stars: ✭ 38 (-72.86%)
Mutual labels:  dependency-injection, asp-net-core
Formhelper
ASP.NET Core - Transform server-side validations to client-side without writing any javascript code. (Compatible with Fluent Validation)
Stars: ✭ 155 (+10.71%)
Mutual labels:  validation, asp-net-core
Validator
The Validator component provides tools to validate values following the JSR-303 Bean Validation specification.
Stars: ✭ 2,238 (+1498.57%)
Mutual labels:  validation, component
Dependency Injection
The DependencyInjection component allows you to standardize and centralize the way objects are constructed in your application.
Stars: ✭ 3,635 (+2496.43%)
Mutual labels:  dependency-injection, component
Csharp Datatables Parser
C# Serverside parser for the popuplar jQuery datatables plugin.
Stars: ✭ 119 (-15%)
Mutual labels:  linq, asp-net-core

FluentValidation.Blazor

Fluent Validation-powered Blazor component for validating standard <EditForm> 🌀 ✅

GitHub Actions NuGet

Install

dotnet add package FluentValidation
dotnet add package Accelist.FluentValidation.Blazor

Getting Started

This library is a direct replacement to the default Blazor <DataAnnotationValidator> with zero configuration required ⚡️ in the application code base:

<EditForm Model="Form">


    <FluentValidator></FluentValidator>


    <div class="form-group">
        <label for="email">Email</label>
        <InputText id="email" type="email" class="form-control" @bind-Value="Form.Email"></InputText>
        <ValidationMessage For="() => Form.Email"></ValidationMessage>
    </div>
    <div class="form-group">
        <button type="submit" class="btn btn-primary">
            <i class="fas fa-chevron-up"></i>
            Submit
        </button>
    </div>
</EditForm>
@code {
    FormModel Form = new FormModel();
}
public class FormModel
{
    public string Email { set; get; }
}

public class FormModelValidator : AbstractValidator<FormModel>
{
    public FormModelValidator()
    {
        RuleFor(Q => Q.Email).NotEmpty().EmailAddress().MaximumLength(255);
    }
}

The <FluentValidator> component automatically detects the Model data type used by the parent <EditForm> then attempts to acquire the corresponding FluentValidation.IValidator<T> for that model data type.

For this reason, in addition to coding the usual FluentValidation.AbstractValidator<T> Fluent Validation implementation, you are required to register the FluentValidation.IValidator<T> implementation in the Startup.cs Service Provider (Dependency Injection):

services.AddTransient<IValidator<CreateAccountFormModel>, CreateAccountFormModelValidator>();
// Alternatively, use FluentValidation.DependencyInjectionExtensions package (read further down below...)

This effectively allows you, dear programmer, to inject required services to your validation implementations for writing amazing custom validation methods! 🔥

public class FormModelValidator : AbstractValidator<FormModel>
{
    readonly AppDbContext DB;
    readonly IServiceProvider SP;

    public FormModelValidator(AppDbContext db, IServiceProvider sp)
    {
        this.DB = db;
        this.SP = sp;

        RuleFor(Q => Q.Email).NotEmpty().EmailAddress().MaximumLength(255)
            .Must(BeUniqueEmail).WithMessage("Email address is already registered.");
    }

    bool BeUniqueEmail(string email)
    {
        var exist = DB.Account.Where(Q => Q.Email == email).Any();
        return (exist == false);
    }
}

Inlined Validator

Validator parameter may also be passed directly to the component to inline the AbstractValidator implementation instead of relying on .NET Core DI:

<FluentValidator Validator="Validator"></FluentValidator>
@code {
    FormModelValidator Validator = new FormModelValidator();
}

FluentValidation.DependencyInjectionExtensions

dotnet add package FluentValidation.DependencyInjectionExtensions
services.AddValidatorsFromAssemblyContaining<Program>();

Can be used to auto-populate all validators from current application / other project automatically!

Nested Objects & Arrays Validation

FluentValidation offers SetValidator method for validating nested objects and arrays. Combined with Dependency Injection capability of this component library, a complex form can be validated easily:

public class RootValidator : AbstractValidator<Root>
{
    public RootValidator(IValidator<Child> childValidator, IValidator<Item> itemValidator)
    {
        RuleFor(Q => Q.Child).SetValidator(childValidator);
        RuleForEach(Q => Q.ArrayOfItems).SetValidator(itemValidator); // Array, List, IList, ...
    }
}

The validators used MUST be registered in the ASP.NET Core service provider!

If for some reason Dependency Injection is not possible, the parameter ChildValidators (inlined Dictionary<Type, IValidator> defining validators used for each children model types) MUST be passed into the component due to technical reasons.

Repeated Remote Call Warning ⚠️

By default, Fluent Validation does NOT short-circuit the validation chain on first error.

This may cause performance issues when a validation logic hits the database / remote service multiple times in short burst due to validation triggers on field change!

To reduce the impact of repeated custom validation calls, use:

  • .Cascade(CascadeMode.Stop) after RuleFor() chain,

  • Or set ValidatorOptions.CascadeMode = CascadeMode.Stop; on Program.cs application entry point.

Why Not Just Use <DataAnnotationValidator>?

  1. <DataAnnotationValidator> cannot use DI services at the moment...

  2. ... but <DataAnnotationValidator> also cannot do AddModelError() like Razor Pages. Which rules out validation AFTER form submission!

  3. [ValidationAttribute] top-level IsValid() method cannot be async!

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].