使用FluentValidation在字段集合上进行验证(而不是在验证器模型上) [英] Using FluentValidation to validate on a collection of Fields (rather than on a validator model)

查看:657
本文介绍了使用FluentValidation在字段集合上进行验证(而不是在验证器模型上)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图查看是否有使用FluentValidation的方法,而无需在我的应用程序中为每种对象类型显式创建验证模型.

在技术上和目前可行吗?

Is this technically and currently possible?

已更新

换句话说,FluentValidation是否可以在没有IValidator上下文的情况下验证规则?相反,我想传递要验证的项目实例,并使用即时构建的验证规则.

To rephrase this, is it possible for FluentValidation to validate Rules WITHOUT a IValidator context? Instead, i would like to pass in the item instance to be validated and use validation Rules which are constructed on-the-fly.

已解决

我能够通过采取一种破解解决方案来解决.这是 我所做的基本细节:

I was able to resolve by doing a kind of a hack solution. Here are basic details of what i did:

1)我创建了一个具有对象集合的类(GenericModel) 表示模型中的属性. 2)我创建了一个验证器类 继承自AbstractValidator. 3)基于 GenericModel的属性对象"和其他元数据的集合 关于每个属性的验证规则和错误消息,我能够 在运行时添加FluentValues规则. 4).在EditForm i 处理了OnSubmit事件.在该事件处理程序中,我执行验证 通过FluentValidation的ValidateAsync()方法. 5).最后,我反复 通过验证结果并使用适当的字段更新每个字段 CSS,错误消息,突出显示...等.

1) I created a class (GenericModel) which has a collection of objects representing properties in a model. 2) I created a validator class that inherits from AbstractValidator. 3) Based on GenericModel's collection of "property objects" + additional metadata about each property's validation rules and error messages, i was able to add FluentValues Rules, all at run-time. 4). At the EditForm i handled the OnSubmit event. In that event handler i execute validation via FluentValidation's ValidateAsync() method. 5). Finally, i iterate thru the validation results and update each field with appropriate CSS, error messages, highlighting...etc.

推荐答案

我能够通过执行一种黑客解决方案来解决.这是我所做的基本细节:

I was able to resolve by doing a kind of a hack solution. Here are basic details of what i did:

  1. 我创建了一个类(GenericModel),该类具有表示模型属性的对象的集合.

  1. I created a class (GenericModel) which has a collection of objects representing properties in a model.

我创建了一个继承自AbstractValidator的验证器类.

I created a validator class that inherits from AbstractValidator.

基于GenericModel的属性对象"集合以及有关每个属性的验证规则和错误消息的其他元数据,我能够在运行时添加FluentValues规则.

Based on GenericModel's collection of "property objects" + additional metadata about each property's validation rules and error messages, i was able to add FluentValues Rules, all at run-time.

在EditForm上,我处理了OnSubmit事件.在该事件处理程序中,我通过FluentValidation的ValidateAsync()方法执行验证.

At the EditForm i handled the OnSubmit event. In that event handler i execute validation via FluentValidation's ValidateAsync() method.

最后,我遍历验证结果并使用适当的CSS,错误消息,突出显示...等更新每个字段.

Finally, i iterate thru the validation results and update each field with appropriate CSS, error messages, highlighting...etc.

这篇关于使用FluentValidation在字段集合上进行验证(而不是在验证器模型上)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆