[英]ASP.NET MVC 3 Pattern for dynamic validation attributes including client side
My validation requirements for a the fields in a form are contained in an external table so that they can be updated without altering and rebuilding the code. 我对表单中字段的验证要求包含在外部表中,以便可以在不更改和重建代码的情况下更新它们。
I have approximatley 100 fields with a mixture of validation requirements - range, required, regular expression and dependency on other fields. 我有大约100个字段,其中包含验证要求-范围,要求,正则表达式以及对其他字段的依赖。 One example is date range validation.
一个示例是日期范围验证。 A date of birth field requires a date range which is between -10 years and -50 years of the current date.
出生日期字段要求的日期范围是当前日期的-10年到-50年之间。
I have read around the subject but have not identified a pattern for the complete solution. 我已阅读了有关该主题的内容,但尚未确定完整解决方案的模式。
I am using Visual Studio 2010 with MVC 3 and Entity Framework. 我将Visual Studio 2010与MVC 3和Entity Framework结合使用。
Any help with this would be gratefully received. 对此将有任何帮助。 Thanks in advance.
提前致谢。
In a simple level I think you can still use the built-in Data-Annotations validation attributes to does the validation and for that you should map the validation rules stored in the table to the attributes. 在简单的层次上,我认为您仍然可以使用内置的Data-Annotations验证属性来进行验证,为此,您应该将表中存储的验证规则映射到这些属性。
I think all you have to do is create a custom model validation provider by inheriting the class ModelValidatorProvider
. 我认为您所要做的就是通过继承
ModelValidatorProvider
类来创建自定义模型验证提供程序。 This class contains a single method called GetValidators
that returns the collection validators for that model. 此类包含一个名为
GetValidators
方法,该方法返回该模型的集合验证器。
You have to implement the GetValidators
method and in there you have to make a database call to get the validation rules for the model from the database (or from cache?) and convert them into ModelValidator
s. 您必须实现
GetValidators
方法,在其中必须进行数据库调用以从数据库(或从缓存?)获取模型的验证规则,并将其转换为ModelValidator
。 You could still use the built-in DataAnnotationsModelValidator
to do the validations. 您仍然可以使用内置的
DataAnnotationsModelValidator
进行验证。
I would suggest you to look into the source code of DataAnnotationsModelValidatorProvider
that will give you all the information. 我建议您研究一下
DataAnnotationsModelValidatorProvider
的源代码,它将为您提供所有信息。 In that class what they are doing is basically iterating all the validation attributes applied to the model properties and converting them into ModelValidator
s through adapters and factories. 在该类中,他们所做的基本上是迭代应用于模型属性的所有验证属性,并通过适配器和工厂将它们转换为
ModelValidator
。 In your case instead of attributes they are stored as records in tables and I don't think much work will be there. 就您而言,它们不是属性而是作为记录存储在表中,我认为不会有太多工作要做。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.