- Принудительная проверка на уровне кода Imperative Code-Based Validation
- Использование проверки на основе кода Using Code-Based Validation
- Overview of how to validate user input (Windows Forms .NET)
- MaskedTextBox Control
- Event-driven validation
- Event-driven validation data-bound controls
- Implicit and explicit validation
- Implicit validation
- Explicit validation
- Default implicit validation behavior for controls
- Closing the form and overriding Validation
- User Input Validation in Windows Forms
- Validation with the MaskedTextBox Control
- Event-Driven Validation
- Data Binding and Event-Driven Validation
- Implicit and Explicit Validation
- Implicit Validation
- Explicit Validation
- Default Implicit Validation Behavior for Windows Forms Controls
- Closing the Form and Overriding Validation
Принудительная проверка на уровне кода Imperative Code-Based Validation
Проверка в императивном коде доступна для действий, производных от CodeActivity, AsyncCodeActivity и NativeActivity, и служит простым способом автономной проверки действия. Imperative code-based validation provides a simple way for an activity to provide validation about itself, and is available for activities that derive from CodeActivity, AsyncCodeActivity, and NativeActivity. Код проверки, определяющий все ошибки и предупреждения проверки, добавляется к действию. Validation code that determines any validation errors or warnings is added to the activity.
Использование проверки на основе кода Using Code-Based Validation
Проверка на основе кода поддерживается действиями, которые являются производными от CodeActivity, AsyncCodeActivity и NativeActivity. Code-based validation is supported by activities that derive from CodeActivity, AsyncCodeActivity, and NativeActivity. Код проверки можно поместить в переопределение метода CacheMetadata, при этом ошибки и предупреждения проверки могут быть добавлены к аргументу метаданных. Validation code can be placed in the CacheMetadata override, and validation errors or warnings can be added to the metadata argument. В следующем примере, если значение Cost больше Price , к метаданным добавляется ошибка проверки. In the following example, if the Cost is greater than the Price , a validation error is added to the metadata.
Обратите внимание, что Cost и Price являются не аргументами для действия, а свойствами, задаваемыми во время разработки. Note that Cost and Price are not arguments to the activity, but are properties that are set at design time. Поэтому их значения можно проверить в переопределенном методе действия CacheMetadata. That is why their values can be validated in the CacheMetadata override. Значение потока данных, проходящее через аргумент, не может быть проверено во время разработки, поскольку данные не будут поступать до времени выполнения, но аргументы действия можно проверить, чтобы убедиться, что они связаны, с помощью атрибута RequiredArgument и групп перегруженных вариантов. The value of the data flowing through an argument cannot be validated at design time because the data does not flow until run time, but activity arguments can be validated to ensure that they are bound by using the RequiredArgument attribute and overload groups. В этом примере код видит атрибут RequiredArgument для аргумента Description и, если он не связан, формируется ошибка проверки. This example code sees the RequiredArgument attribute for the Description argument, and if it is not bound then a validation error is generated. Обязательные аргументы рассматриваются в обязательных аргументах и группах перегрузок. Required arguments are covered in Required Arguments and Overload Groups.
По умолчанию ошибка проверки добавляется к метаданным при вызове AddValidationError. By default, a validation error is added to the metadata when AddValidationError is called. Чтобы добавить предупреждение проверки, используйте перегрузку AddValidationError, принимающую ValidationError, и укажите, что ValidationError представляет предупреждение, задав свойство IsWarning. To add a validation warning, use the AddValidationError overload that takes a ValidationError, and specify that the ValidationError represents a warning by setting the IsWarning property.
Когда рабочий процесс модифицируется в конструкторе, выполняется проверка и любые ошибки или предупреждения, выявленные в ее ходе, отображаются в конструкторе. Validation occurs when a workflow is modified in the workflow designer and any validation errors or warnings are displayed in the workflow designer. Также проверка происходит во время выполнения, когда вызывается рабочий процесс, и при появлении каких-либо ошибок проверки логикой проверки по умолчанию выдается исключение InvalidWorkflowException. Validation also occurs at run time when a workflow is invoked and if any validation errors occur, an InvalidWorkflowException is thrown by the default validation logic. Дополнительные сведения о вызове проверки и получении доступа к любым предупреждениям или ошибкам проверки см. в разделе вызов проверки активности. For more information about invoking validation and accessing any validation warnings or errors, see Invoking Activity Validation.
Исключения, вызванные в методе CacheMetadata, не считаются ошибками проверки. Any exceptions that are thrown from CacheMetadata are not treated as validation errors. Эти исключения перейдут из метода Validate к вызывающему объекту, который должен их обработать. These exceptions will escape from the call to Validate and must be handled by the caller.
Проверка на основе кода используется для проверки действий, которые содержат код, но для нее недоступны другие действия в рабочем процессе. Code-based validation is useful for validating the activity that contains the code, but it does not have visibility into the other activities in the workflow. Проверка декларативных ограничений дает возможность проверять связи между действием и другими действиями в рабочем процессе и рассматривается в разделе декларативные ограничения . Declarative constraints validation provides the ability to validate the relationships between an activity and other activities in the workflow, and is covered in the Declarative Constraints topic.
Overview of how to validate user input (Windows Forms .NET)
When users enter data into your application, you may want to verify that the data is valid before your application uses it. You may require that certain text fields not be zero-length, that a field formatted as a telephone number, or that a string doesn’t contain invalid characters. Windows Forms provides several ways for you to validate input in your application.
The Desktop Guide documentation for .NET 5 (and .NET Core) is under construction.
MaskedTextBox Control
If you need to require users to enter data in a well-defined format, such as a telephone number or a part number, you can accomplish this quickly and with minimal code by using the MaskedTextBox control. A mask is a string made up of characters from a masking language that specifies which characters can be entered at any given position in the text box. The control displays a set of prompts to the user. If the user types an incorrect entry, for example, the user types a letter when a digit is required, the control will automatically reject the input.
The masking language that is used by MaskedTextBox is flexible. It allows you to specify required characters, optional characters, literal characters, such as hyphens and parentheses, currency characters, and date separators. The control also works well when bound to a data source. The Format event on a data binding can be used to reformat incoming data to comply with the mask, and the Parse event can be used to reformat outgoing data to comply with the specifications of the data field.
Event-driven validation
If you want full programmatic control over validation, or need complex validation checks, you should use the validation events that are built into most Windows Forms controls. Each control that accepts free-form user input has a Validating event that will occur whenever the control requires data validation. In the Validating event-handling method, you can validate user input in several ways. For example, if you have a text box that must contain a postal code, you can do the validation in the following ways:
If the postal code must belong to a specific group of zip codes, you can do a string comparison on the input to validate the data entered by the user. For example, if the postal code must be in the set <10001, 10002, 10003>, then you can use a string comparison to validate the data.
If the postal code must be in a specific form, you can use regular expressions to validate the data entered by the user. For example, to validate the form ##### or #####-#### , you can use the regular expression ^(\d<5>)(-\d<4>)?$ . To validate the form A#A #A# , you can use the regular expression [A-Z]\d[A-Z] \d[A-Z]\d . For more information about regular expressions, see .NET Regular Expressions and Regular Expression Examples.
If the postal code must be a valid United States Zip code, you could call a Zip code Web service to validate the data entered by the user.
The Validating event is supplied an object of type CancelEventArgs. If you determine that the control’s data isn’t valid, cancel the Validating event by setting this object’s Cancel property to true . If you don’t set the Cancel property, Windows Forms will assume that validation succeeded for that control and raise the Validated event.
For a code example that validates an email address in a TextBox, see the Validating event reference.
Event-driven validation data-bound controls
Validation is useful when you have bound your controls to a data source, such as a database table. By using validation, you can make sure that your control’s data satisfies the format required by the data source, and that it doesn’t contain any special characters such as quotation marks and back slashes that might be unsafe.
When you use data binding, the data in your control is synchronized with the data source during execution of the Validating event. If you cancel the Validating event, the data won’t be synchronized with the data source.
If you have custom validation that takes place after the Validating event, it won’t affect the data binding. For example, if you have code in a Validated event that attempts to cancel the data binding, the data binding will still occur. In this case, to perform validation in the Validated event, change the control’s Binding.DataSourceUpdateMode property from DataSourceUpdateMode.OnValidation to DataSourceUpdateMode.Never, and add your-control.DataBindings[«field-name»].WriteValue() to your validation code.
Implicit and explicit validation
So when does a control’s data get validated? This is up to you, the developer. You can use either implicit or explicit validation, depending on the needs of your application.
Implicit validation
The implicit validation approach validates data as the user enters it. Validate the data by reading the keys as they’re pressed, or more commonly whenever the user takes the input focus away from the control. This approach is useful when you want to give the user immediate feedback about the data as they’re working.
If you want to use implicit validation for a control, you must set that control’s AutoValidate property to EnablePreventFocusChange or EnableAllowFocusChange. If you cancel the Validating event, the behavior of the control will be determined by what value you assigned to AutoValidate. If you assigned EnablePreventFocusChange, canceling the event will cause the Validated event not to occur. Input focus will remain on the current control until the user changes the data to a valid format. If you assigned EnableAllowFocusChange, the Validated event won’t occur when you cancel the event, but focus will still change to the next control.
Assigning Disable to the AutoValidate property prevents implicit validation altogether. To validate your controls, you’ll have to use explicit validation.
Explicit validation
The explicit validation approach validates data at one time. You can validate the data in response to a user action, such as clicking a Save button or a Next link. When the user action occurs, you can trigger explicit validation in one of the following ways:
- Call Validate to validate the last control to have lost focus.
- Call ValidateChildren to validate all child controls in a form or container control.
- Call a custom method to validate the data in the controls manually.
Default implicit validation behavior for controls
Different Windows Forms controls have different defaults for their AutoValidate property. The following table shows the most common controls and their defaults.
Control | Default Validation Behavior |
---|---|
ContainerControl | Inherit |
Form | EnableAllowFocusChange |
PropertyGrid | Property not exposed in Visual Studio |
ToolStripContainer | Property not exposed in Visual Studio |
SplitContainer | Inherit |
UserControl | EnableAllowFocusChange |
Closing the form and overriding Validation
When a control maintains focus because the data it contains is invalid, it’s impossible to close the parent form in one of the usual ways:
- By clicking the Close button.
- By selecting the System >Close menu.
- By calling the Close method programmatically.
However, in some cases, you might want to let the user close the form regardless of whether the values in the controls are valid. You can override validation and close a form that still contains invalid data by creating a handler for the form’s FormClosing event. In the event, set the Cancel property to false . This forces the form to close. For more information and an example, see Form.FormClosing.
If you force the form to close in this manner, any data in the form’s controls that has not already been saved is lost. In addition, modal forms don’t validate the contents of controls when they’re closed. You can still use control validation to lock focus to a control, but you don’t have to be concerned about the behavior associated with closing the form.
User Input Validation in Windows Forms
When users enter data into your application, you may want to verify that the data is valid before your application uses it. You may require that certain text fields not be zero-length, that a field be formatted as a telephone number or other type of well-formed data, or that a string not contain any unsafe characters that could be used to compromise the security of a database. Windows Forms provides several ways for you to validate input in your application.
Validation with the MaskedTextBox Control
If you need to require users to enter data in a well-defined format, such as a telephone number or a part number, you can accomplish this quickly and with minimal code by using the MaskedTextBox control. A mask is a string made up of characters from a masking language that specifies which characters can be entered at any given position in the text box. The control displays a set of prompts to the user. If the user types an incorrect entry, for example, the user types a letter when a digit is required, the control will automatically reject the input.
The masking language that is used by MaskedTextBox is very flexible. It allows you to specify required characters, optional characters, literal characters, such as hyphens and parentheses, currency characters, and date separators. The control also works well when bound to a data source. The Format event on a data binding can be used to reformat incoming data to comply with the mask, and the Parse event can be used to reformat outgoing data to comply with the specifications of the data field.
Event-Driven Validation
If you want full programmatic control over validation, or need to perform complex validation checks, you should use the validation events built into most Windows Forms controls. Each control that accepts free-form user input has a Validating event that will occur whenever the control requires data validation. In the Validating event-handling method, you can validate user input in several ways. For example, if you have a text box that must contain a postal code, you can perform the validation in the following ways:
If the postal code must belong to a specific group of zip codes, you can perform a string comparison on the input to validate the data entered by the user. For example, if the postal code must be in the set <10001, 10002, 10003>, then you can use a string comparison to validate the data.
If the postal code must be in a specific form you can use regular expressions to validate the data entered by the user. For example, to validate the form ##### or #####-#### , you can use the regular expression ^(\d<5>)(-\d<4>)?$ . To validate the form A#A #A# , you can use the regular expression [A-Z]\d[A-Z] \d[A-Z]\d . For more information about regular expressions, see .NET Framework Regular Expressions and Regular Expression Examples.
If the postal code must be a valid United States Zip code, you could call a Zip code Web service to validate the data entered by the user.
The Validating event is supplied an object of type CancelEventArgs. If you determine that the control’s data is not valid, you can cancel the Validating event by setting this object’s Cancel property to true . If you do not set the Cancel property, Windows Forms will assume that validation succeeded for that control, and raise the Validated event.
For a code example that validates an email address in a TextBox, see Validating.
Data Binding and Event-Driven Validation
Validation is very useful when you have bound your controls to a data source, such as a database table. By using validation, you can make sure that your control’s data satisfies the format required by the data source, and that it does not contain any special characters such as quotation marks and back slashes that might be unsafe.
When you use data binding, the data in your control is synchronized with the data source during execution of the Validating event. If you cancel the Validating event, the data will not be synchronized with the data source.
If you have custom validation that takes place after the Validating event, it will not affect the data binding. For example, if you have code in a Validated event that attempts to cancel the data binding, the data binding will still occur. In this case, to perform validation in the Validated event, change the control’s Data Source Update Mode property (under (Databindings)\(Advanced)) from OnValidation to Never, and add Control .DataBindings[» «].WriteValue() to your validation code.
Implicit and Explicit Validation
So when does a control’s data get validated? This is up to you, the developer. You can use either implicit or explicit validation, depending on the needs of your application.
Implicit Validation
The implicit validation approach validates data as the user enters it. You can validate the data as the data is entered in a control by reading the keys as they are pressed, or more commonly whenever the user takes the input focus away from one control and moves to the next. This approach is useful when you want to give the user immediate feedback about the data as they are working.
If you want to use implicit validation for a control, you must set that control’s AutoValidate property to EnablePreventFocusChange or EnableAllowFocusChange. If you cancel the Validating event, the behavior of the control will be determined by what value that you assigned to AutoValidate. If you assigned EnablePreventFocusChange, canceling the event will cause the Validated event not to occur. Input focus will remain on the current control until the user changes the data to a valid input. If you assigned EnableAllowFocusChange, the Validated event will not occur when you cancel the event, but focus will still change to the next control.
Assigning Disable to the AutoValidate property prevents implicit validation altogether. To validate your controls, you will have to use explicit validation.
Explicit Validation
The explicit validation approach validates data at one time. You can validate the data in response to a user action, such as clicking a Save button or a Next link. When the user action occurs, you can trigger explicit validation in one of the following ways:
Call Validate to validate the last control to have lost focus.
Call ValidateChildren to validate all child controls in a form or container control.
Call a custom method to validate the data in the controls manually.
Default Implicit Validation Behavior for Windows Forms Controls
Different Windows Forms controls have different defaults for their AutoValidate property. The following table shows the most common controls and their defaults.
Control | Default Validation Behavior |
---|---|
ContainerControl | Inherit |
Form | EnableAllowFocusChange |
PropertyGrid | Property not exposed in Visual Studio |
ToolStripContainer | Property not exposed in Visual Studio |
SplitContainer | Inherit |
UserControl | EnableAllowFocusChange |
Closing the Form and Overriding Validation
When a control maintains focus because the data it contains is invalid, it is impossible to close the parent form in one of the usual ways:
By clicking the Close button.
By selecting Close in the System menu.
By calling the Close method programmatically.
However, in some cases, you might want to let the user close the form regardless of whether the values in the controls are valid. You can override validation and close a form that still contains invalid data by creating a handler for the form’s FormClosing event. In the event, set the Cancel property to false . This forces the form to close. For more information and an example, see Form.FormClosing.
If you force the form to close in this manner, any data in the form’s controls that has not already been saved is lost. In addition, modal forms do not validate the contents of controls when they are closed. You can still use control validation to lock focus to a control, but you do not have to be concerned about the behavior associated with closing the form.