> 技术文档 > 学习016-03 Declare Validation Rules(声明验证规则)

学习016-03 Declare Validation Rules(声明验证规则)


Declare Validation Rules(声明验证规则

This topic describes two ways to declare and apply rules that validate business objects and their property values:
本主题介绍了两种声明和应用规则的方法,这些规则用于验证业务对象及其属性值:

  • Apply Validation Rules in Code(在代码中应用验证规则)
    Use this solution if you want to modify sources of the required business classes.
    如果您想修改所需业务类的源代码,请使用此解决方案。

  • Apply Validation Rules in the Model Editor(在模型编辑器中应用验证规则)
    Use this solution to declare a Validation Rule for a business class whose source code cannot be modified (e.g., a business class declared in a third-party module).
    使用此解决方案为无法修改其源代码的业务类(例如,在第三方模块中声明的业务类)声明验证规则。

Note
Before you implement one of these solutions, ensure that you added a Validation Module to a module project.

在实施这些解决方案之一之前,请确保已将验证模块添加到模块项目中。

Requirements for Non-Persistent Objects(非持久化对象的要求)

If you want to validate non-persistent objects in the Save or Delete Context, ensure that the following conditions are met.
如果要在保存或删除上下文环境中验证非持久化对象,请确保满足以下条件。

1.The non-persistent class implements the INotifyPropertyChanged interface or is inherited from the NonPersistentBaseObject or NonPersistentLiteObject class.
非持久化类实现了INotifyPropertyChanged接口,或者继承自NonPersistentBaseObject类或NonPersistentLiteObject类。

2.The static AutoSetModifiedOnObjectChangeByDefault field or AutoSetModifiedOnObjectChange property is set to true.
静态的AutoSetModifiedOnObjectChangeByDefault字段或AutoSetModifiedOnObjectChange属性设置为true。

3.You use the CreateObjectSpace(Type) method to create an Object Space.
你使用CreateObjectSpace(Type)方法来创建一个对象空间。

4.You call the CreateObject() or GetObject(Object) method to get a non-persistent object.
你调用CreateObject() 或GetObject(Object) 方法来获取一个非持久化对象。

5.If you want to use a validated value of a non-persistent object property, you handle the BaseObjectSpace.ObjectSaving, BaseObjectSpace.ObjectSaved, or BaseObjectSpace.Committed event. These events are raised after successful validation. Note that the ActionBase.Executed event is raised before validation occurs.
如果要使用非持久化对象属性的已验证值,可以处理BaseObjectSpace.ObjectSaving、BaseObjectSpace.ObjectSaved或BaseObjectSpace.Committed事件。这些事件会在成功验证后引发。请注意,ActionBase.Executed事件会在验证发生之前引发。

Apply Validation Rules in Code(在代码中应用验证规则)

To apply a specific Rule to a class or a property, add an attribute with the same name as the required Rule. To see the full list of built-in attributes, refer to the following help topic: Validation Rules. An attribute’s parameters allow you to specify a Rule’s properties. For example, the ContextIDs parameter allows you to specify a Context for a Rule.
要将特定规则应用于类或属性,请添加一个与所需规则同名的特性。若要查看内置特性的完整列表,请参阅以下帮助主题:验证规则。特性的参数允许您指定规则的属性。例如,ContextIDs 参数允许您为规则指定上下文。

You can apply Rule attributes only to public members of a business class.
您只能将规则属性应用于业务类的公共成员。

The code below applies the RuleCriteria Rule to the Incident persistent class and the RuleRequiredField Rule to the Incident.Subject property. Both Rules are checked when you save this object. They also check if the property values are null (Nothing in VB) because the SkipNullOrEmptyValues parameter of these Rules is set to false (for the second Rule, it is the default value).
下面的代码将RuleCriteria规则应用于Incident持久化类,并将RuleRequiredField规则应用于Incident.Subject属性。在保存此对象时,将检查这两个规则。由于这些规则的SkipNullOrEmptyValues参数设置为false(对于第二个规则,这是默认值),它们还会检查属性值是否为null(在VB中为Nothing)。

C# (EF Core)using System.ComponentModel;using DevExpress.Persistent.Validation;//...[DefaultClassOptions][DefaultProperty(nameof(Subject))][RuleCriteria(\"RuleCriteria for Incident\", DefaultContexts.Save, \"AssignedTo is not null\", SkipNullOrEmptyValues = false)]public class Incident : BaseObject { [RuleRequiredField(\"RuleRequiredField for Incident.Subject\", DefaultContexts.Save)] public virtual string Subject { get; set; } public virtual Person AssignedTo { get; set; }}[DefaultClassOptions]public class Person : BaseObject { public virtual string FirstName { get; set; } public virtual string LastName { get; set; } // ...}// Make sure that you use options.UseChangeTrackingProxies() in your DbContext settings.
C# (XPO)using System.ComponentModel;using DevExpress.Persistent.Validation;//...[DefaultClassOptions][DefaultProperty(nameof(Subject))][RuleCriteria(\"RuleCriteria for Incident\", DefaultContexts.Save, \"AssignedTo is not null\", SkipNullOrEmptyValues = false)]public class Incident : BaseObject { public Incident(Session session) : base(session) { } private Person assignedTo; private string subject; [RuleRequiredField(\"RuleRequiredField for Incident.Subject\", DefaultContexts.Save)] public string Subject { get { return subject; } set { SetPropertyValue(nameof(Subject), ref subject, value); } } public Person AssignedTo { get { return assignedTo; } set { SetPropertyValue(nameof(AssignedTo), ref assignedTo, value); } }}

To customize Validation Rules, use the PersistenceValidationController. Refer to its description to find an example of how to use this Controller.
要自定义验证规则,请使用持久化验证控制器。请参考其说明,以找到如何使用此控制器的示例。

If a value does not pass validation, an editor shows the Validation_SignWeb icon. The Validation Error pop-up dialog displays a brief description of each error.
如果某个值未通过验证,编辑器会显示“验证_SignWeb”图标。“验证错误”弹出对话框会显示每个错误的简要说明。

  • In WinForms applications, a pop-up window shows the RuleSetValidationResultItem_ByTarget List View if a broken Validation Rule is detected. This List View details all broken Rules.
    在Windows窗体应用程序中,如果检测到验证规则失效,将弹出一个窗口显示“RuleSetValidationResultItem_ByTarget”列表视图。此列表视图会详细列出所有失效的规则。
    学习016-03 Declare Validation Rules(声明验证规则)

You can double click a record to view detailed information on a broken Rule and validation results.
您可以双击一条记录,查看有关失效规则和验证结果的详细信息。
学习016-03 Declare Validation Rules(声明验证规则)

  • ASP.NET Web Forms applications display information on broken Rules in a Detail View where you edit an object.
    ASP.NET Web Forms应用程序会在用于编辑对象的详细信息视图中显示有关违反规则的信息。
    学习016-03 Declare Validation Rules(声明验证规则)

  • If a Rule is broken in an editable List View, details about this Rule are displayed below the corresponding row.
    如果在可编辑列表视图中违反了某项规则,该规则的详细信息将显示在相应行下方。
    学习016-03 Declare Validation Rules(声明验证规则)

You can also specify custom text for Rule messages. To do this, set the Rule attribute’s messageTemplate parameter in code or change the Rules | Rule node’s CustomMessageTemplate property in the Model Editor.
你还可以为规则消息指定自定义文本。要做到这一点,可以在代码中设置规则属性的messageTemplate参数,或者在模型编辑器中更改“规则”|“规则”节点的“自定义消息模板”属性。

Apply Validation Rules in the Model Editor(在模型编辑器中应用验证规则)

You can use the Model Editor to declare a Validation Rule in the Application Model. The following Application Model nodes define Contexts and Rules:
你可以使用模型编辑器在应用程序模型中声明验证规则。以下应用程序模型节点定义了上下文和规则:

  • ActionDesign | Actions | (动作设计 | 动作 | )
    Specify the node’s ValidationContexts property to use this Action as a Context with the specified ID.
    指定节点的“ValidationContexts”属性,以便将此操作用作具有指定ID的上下文。

  • Validation | Contexts(验证 | 上下文)
    Use this node to localize Context captions. These captions are displayed in Views that show Rules objects. These objects contain information on Rules and Contexts used in your application. You can make these objects available in your application for administrative purposes. To localize a Context, select the Add… | ValidationContext item in the context menu of the Contexts node, and specify the ID and Caption properties.
    使用此节点对上下文标题进行本地化。这些标题显示在显示规则对象的视图中。这些对象包含有关应用程序中使用的规则和上下文的信息。出于管理目的,您可以在应用程序中使用这些对象。要对上下文进行本地化,请在“上下文”节点的上下文菜单中选择“添加… | 验证上下文”项,然后指定“ID”和“标题”属性。

  • Validation | ErrorMessageTemplates(验证 | 错误消息模板)
    This node allows you to change the default message template for a Rule type. Error messages show the new text when a Rule of this type is broken. Note that the CustomMessageTemplate property of Rules | Rule nodes and a Rule attribute’s CustomMessageTemplate parameter override this text.
    此节点允许您更改规则类型的默认消息模板。当违反此类型的规则时,错误消息将显示新文本。请注意,“规则|规则”节点的“自定义消息模板”属性以及规则属性的“自定义消息模板”参数会覆盖此文本。

  • Validation | Rules(验证 | 规则)
    This node contains Rules from this Module, and all referenced Modules, and allows you to define custom Rules. You can add a Rule (RuleRequiredField, RuleRange, etc.) from the corresponding Add… context menu item and specify the new Rule’s properties. All Rules have a ContextIDs property. Set this property to an Action’s ValidationContexts property value or a Context identifier. You can also use the DefaultContexts.Save or DefaultContexts.Delete Context for Rules of any type.
    此节点包含来自本模块以及所有引用模块的规则,并允许您定义自定义规则。您可以从相应的“添加…”上下文菜单项中添加规则(必填字段规则、范围规则等),并指定新规则的属性。所有规则都有一个“上下文 ID”属性。将此属性设置为某个操作的“验证上下文”属性值或某个上下文标识符。您还可以对任何类型的规则使用“默认上下文.保存”或“默认上下文.删除”上下文。

Invoke the Model Editor for a project that references a Validation Module to find information on Rules applied in code. This information is also available in a module where Rules are applied. This allows an application administrator to add and edit Rules and Contexts in the Model Editor. Note that this user must have access to the Model Editor. The following image shows how the Model Editor shows the Rules defined in the Apply Rule Attributes in Code section.
调用引用验证模块的项目的模型编辑器,以查找有关代码中应用规则的信息。在应用规则的模块中也可以获取此信息。这使得应用程序管理员能够在模型编辑器中添加和编辑规则及上下文。请注意,此用户必须有权访问模型编辑器。下图展示了模型编辑器如何显示“在代码中应用规则属性”部分中定义的规则。
学习016-03 Declare Validation Rules(声明验证规则)

Soft Validation(软验证)

You can define Soft Validation Rules - Rules that end users can ignore. Use Soft Validation to warn users that data is invalid, but allow them to commit changes anyway. Set the IRuleBaseProperties.ResultType property to Warning or Information to define an ignorable Rule in the Model Editor. To define this Rule in code, set the RuleBaseAttribute.ResultType parameter to Warning or Information. For more information on result types, refer to the following enumeration description: ValidationResultType.
你可以定义软验证规则 - 即最终用户可以忽略的规则。使用软验证来警告用户数据无效,但仍允许他们提交更改。在模型编辑器中,将IRuleBaseProperties.ResultType属性设置为“Warning”(警告)或“Information”(信息),以定义一个可忽略的规则。要在代码中定义此规则,将RuleBaseAttribute.ResultType参数设置为“Warning”(警告)或“Information”(信息)。有关结果类型的更多信息,请参阅以下枚举说明:ValidationResultType。

Note

  • Populate the IRule.UsedProperties collection with names of properties to be validated and highlighted in the UI if a warning or info Rule is broken.
    使用要验证的属性名称填充IRule.UsedProperties集合,如果警告或信息规则被破坏,这些属性将在用户界面中突出显示。
  • List Views in ASP.NET Web Forms applications do not support Soft Validation.
    ASP.NET Web Forms应用程序中的列表视图不支持软验证。
  • Set the ValidationModule.IgnoreWarningAndInformationRules property to true if you want to disable Soft Validation Rules so that a user is not notified if these Rules are broken.
    如果你想禁用软验证规则,以便在违反这些规则时不通知用户,请将ValidationModule.IgnoreWarningAndInformationRules属性设置为true。

The Validation | Soft Validation section of the FeatureCenter demo demonstrates how to implement and use Soft Validation. The default location of the application is %PUBLIC%\\Documents\\DevExpress Demos 24.1\\Components\\XAF\\FeatureCenter.NETFramework.XPO.
FeatureCenter 演示的“验证 | 软验证”部分展示了如何实现和使用软验证。该应用程序的默认位置是 %PUBLIC%\\Documents\\DevExpress Demos 24.1\\Components\\XAF\\FeatureCenter.NETFramework.XPO。

Define a Custom Rule Source(定义自定义规则源)

To create a custom Validation Rule Source, define a class that implements the IRuleSource interface. The interface’s IRuleSource.CreateRules method allows you to implement custom logic to instantiate Validation Rules.
要创建自定义验证规则源,请定义一个实现IRuleSource接口的类。该接口的IRuleSource.CreateRules方法允许您实现自定义逻辑来实例化验证规则。

Refer to the following interface description to see how to implement a custom Validation Rule Source: IRuleSource.
参考以下接口描述,了解如何实现自定义验证规则源:IRuleSource。