Input validation in Winforms - winforms

In good old MFC, the DDX routines would have built in validation for form entries. For example it was possible to automatically check if the user entered a string in a text box meant for numeric input.
Is there any such mechanism in Winforms? Obviously one can add handlers for the 'onChange' etc kind of events and do the processing there, but I am asking if there is any built-in mechanism.
thanks

You could certainly implement your own ValidatingTextBox with a Regex property which is validated, essentially, whenever you decide you want it to be validated (keystrokes, Enter key, loses focus, ...)
At the simplest level there are Validated and Validating events on the plain TextBox that you can supply handlers to for individual instances.

There have been a couple of attempts to replicate the richer ASP.NET validators on Windows forms. Check out this one by Billy Hollis

No, I don't believe so, but you can easily derive a custom textbox that applies the kind of validation you require based on a parameter or property you set on its instance. Then you'd have a built-in mechanism. ;-)

Related

Prevent user from typing certain char in TextBox

I am using WPF, MVVM-Light.
In my UI I have a textbox, and I want to prevent the user from typing certain characters in the textbox.
I know if we use code-behind I could handle the key down keyPress events, can I achieve it through MVVM?
Can we use some behaviors or some interactivity triggers?
Using code-behind is perfectly OK with MVVM providing the code-behind is related to your View only.
So if you have some view-specific logic that says "User can only type numbers in this box", then it's perfectly OK to write a KeyPress event for the TextBox that only allows numeric keys to be processed. You could even throw this into a UserControl so it can be reusable.
However if your allowed character logic is based on application logic, such as "User can only use the characters defined in the app.config file for this string value", then you'd be better off validating that in the ViewModel.
Also note that restriction is different from validation.
If you want to validate a user's entry, then I would do so using IDataErrorInfo from the ViewModel layer, and possibly a binding with a mode of UpdateSourceTrigger=PropertyChanged so the validation is checked after every key press.
If you want to restrict what characters can be typed into a TextBox, then I would probably do that from the View layer in the code behind, as that is a functionality of the View.
Yes, to filter input the MVVM way, I would suggest either using a custom control (such as a masked TextBox control) or a Behavior.
I was recently looking for a good masked TextBox and there is a free one out there from Xceed which you can find here. I can't speak to this one, as I haven't used it, but I've been happy with other Xceed components I've used in the past.
However I didn't want to go third party and include a bunch of controls I didn't need, so I ended up creating a behavior that simply attaches to the TextBox and filters the input based on a FilterType. The behavior is pretty easy to create, and you simply use the PreviewTextInput event to filter out characters that you don't want.
This SO Answer has a number of suggestions and links to how to filter/mask the input and if you're not familiar with creating Attached Behaviors, this example shows how to create an Attached Behavior for a Masked Text Box.

How to determine if WPF TextBox is dirty (when using UpdateSourceTrigger=LostFocus)

How can I determine when a user has updated the text in a textbox before the Binding has updated the source?
I was expecting to find an "IsDirty" property on either the TextBox or the Binding ...
My problem is that the "Cancel" button Enabled property is bound to the ViewModel's IsDirty property and is disabled until the focus moves out of the textbox.
"IsDirty" needs to be defined as ViewModel.IsDirty || TextBox.IsDirty
WPF can't support the typical IsDirty behaviour that users would expect in a high quality application.
The problem stems from the strange design of the Binder class.
Furthermore WPF architecture is kind of hard-coded to using the default Binder implementation, replacing it is a huge job and requires many "dirty tricks" to work around the endless WPF design flaws.
The easiest way I found to workaround this limitation is to move all value conversion logic to the view model and use UpdateSourceTrigger=PropertyChanged, and implement your own IsDirty and IsInvalid logic and flags.
This approach also plays nicely with Caliburn.Micro
First, why is Cancel disabled? It should be enabled all the time. Any other behavior would be odd. The user should be able to cancel although he hasn't done anything.
Second, I would use Commands so that it can determine whether it can be executed or not based on the state of the viewmodel. Should be easy to implement, if the viewmodel also provide the implementation of the command.
I'd recommend to read some articles and/or tutorials about it. Google for the interface ICommand.
And to answer your question. Assuming you're using binding you could use the INotifyPropertyChanging interface to determine when a value is about to change. You could then store the current value in a backup field or something.
EDIT - Regarding "let him lose data"
Sure it's a valid strategy. Think on a larger input dialog e.g. 5 input controls, which must be validated before persisting the input. I'm assuming that the data is very important according to your arguments. Furthermore, you started to hack your data into the dialog. On input control 3 you decide to press 'ALT + F4'.
First, ask yourself, why did the user press the keys? IMHO he doesn't care about what's happening to his data.
If 'ALT + F4' is just an example for being robust. Forget about it. I think absolute robustness cannot be implemented without being very expensive.
Second, regarding consistency and validity after the restart of the application, you have to throw the data away so that you don't start with an undefined state. Remember, the entity the user began to fill is not valid at this state. Neither the states respectively the values of the properties are.
So IMHO the much better strategy is to restart with a clean and defined state, so that the user is able to continue with whatever you want him to do with your application.
Why is this strategy better? Well, it's much easier to implement. And the much more important argument, the user never gets lost because of an odd state.

WPF Numeric only TextBox - Handle it with event or command?

I am attempting to create a TextBox that only allows numeric characters and a decimal point. I don't need assistance in writing the code, but on the concept. I am using MVVM to design the WPF application and I'm not sure whether to use an event or event-to-command.
I have read several different viewpoints regarding this topic:
(I have found this to be a little extreme and as some have called it "counter-productive", but it upholds the "purity" of MVVM): Never have any code behind your View. To prevent this, use MVVM Light Library. In short, convert events to commands so that everything can be controlled in the ViewModel.
(The second argument does not uphold the (maybe over excessive) "purity" of MVVM): Not everything must be handled in the ViewModel and it is ok to create Events to handle certain UI requirements.
I was leaning more towards the second option because of simplicity and, as I have stated previously, the first option seems a little extreme. In my specific case (creating a numeric only TextBox) would most people prefer either of the above options or one I have not discovered?
You should handle this as an event in .cs file. You are trying to add functionality in a control. Like Text in a TextBox .They all are handeld in .cs file. ViewModel is resposible for holding the data and Behavior based on that Data for View not for the functionality of Control.
This should be handled directly in the View rather than involving the ViewModel, but there's no need to reinvent the wheel.
Depending on your exact numeric requirements, use a control such as DoubleUpDown or IntegerUpDown from the Extended WPF Toolkit (available via NUGet)

WPF: On-screen validation

What technique or library do you recommend for on-screen validation. That is, validation that is very visible to the user.
My requirements:
The validation must have a way to indicate to the user which fields have a problem.
The validation must have a way to indicate to the user how to fix the problem.
The validation must support comparatives like TextboxA > Textbox B.
The validation must support custom logic like "If CheckBoxC is checked, ListBoxD must be empty".
Sometimes, though not always, the user can save a record even though validation fails.
A combination of using IDataErrorInfo and ValidationRules should meet all of your criteria.
1 & 2 - can be handled easily using the standard WPF validation display techniques. For background info, I'd read Josh Smith's MSDN article, in particular, he shows a couple of ways to handle displaying validation information.
3 & 4 - can be handled easily via IDataErrorInfo. This interface lets you do any logic required in order to display validation, and can combine multiple properties in the validation rules.
5 - This is a matter of just tracking which rules prevent saving, and which do not. You'll need to handle this directly, but again, IDataErrorInfo can help here, since you can use a known set that allow saving, and have every other issue prevent it.
For simple cases, Validation Rules make life easy. They can be combined with IDataErrorInfo, however, for a nice mix of simple with extended logic for difficult cases.
You might find the BookLibrary and EmailClient sample applications of the WPF Application Framework (WAF) interesting. They use the IDataErrorInfo interface in combination with the .NET DataAnnotations attributes to define the validation rules.

How to catch and display warnings to the user

Essentially the warning in our case is just a validation, we don't want to mark it as an error just a warning so the user knows. I was hoping to use the same or similar method used for validation. Currently I'm leaning towards implementing IDataErrorInfo. But I'd like to change the style on display and allow saving. Has anyone done anything similar? I don't want 2 separate solutions for validation.
during validation, set some corresponding properties.
eg: IsInWarning and IsInError.
set these properties according to the validation logic in the error handler and then use a datatemplate to style the items with triggers.
something like that?
(sorry no time to mock up an example now...)
WPF has a built-in mechanism for handling validation via IDataErrorInfo.
There is a good CodeProject article describing the process, but it basically comes down to supplying an ErrorTemplate that's used for items in an error state, and telling WPF to validate your objects. If they implement IDataError info, you can have their style change, plus use that to present error messages directly.

Resources