WPF: Validating an object at submission - wpf

I am creating a WPF app using MVVM. The app manages tagged documents, called Notes, similar to blog posts. A Note has a Title, Text and a Tags collection. I want to validate a Note at the time it is submitted for two validation rules:
The Title can't be empty; and
The Note must have at least one Tag.
If validation fails, then the Note submission is canceled, the offending control in the UI should get the familair red outline, and a tool tip should explain the error. This all seems pretty straightforward if one wants to validate at the time a WPF control updates its binding source. Just create a custom ValidationRule and add it to the <Binding.ValidationRules> collection.
My problem is that I want to validate when the Note is submitted, not when controls update their binding sources. I know I can create a custom error message and display it in a MessageBox, but I would much rather use the red outline-tooltip approach--it's less intrusive. I figure there must be some simple way of doing this.
My question is pretty simple: What is the best way of performing on-submission validation in WPF/MVVM? How does my code instruct the UI to show the red error outline when validation fails? Thanks for your help.

One option is to use IDataErrorInfo in conjunction with WPF.
This would make it fairly easy to handle this scenario. You can just setup the IDataErrorInfo information at submission time, which would then cause the "red outline" (or other error theming) to appear.

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.

deterministic and asynchronous field validation in WPF

In my MVVM based application I need to validate fields in a data entry from. If possible, I would like to use the standard WPF validation binding with ErrorTemplates.
However I would like the execution of the validation logic to be completely driven/triggered by the ViewModel (push to the View, not pull by the View) for the following reasons:
It must work asynchronously because validation logic might take a while to execute.
I need to be more deterministic and fine grained when validation logic is to be executed (e.g. only after the user clicks "Apply" or when the internal state changed in a way that entries suddenly become invalid)
I know Silverlight has INotifyDataErrorInfo which was introduced for exactly this purpose, but WPF doesn't. How can I still have my validation logic exectuted deterministically and asynchronously?
I posted an answer on your other question that apparently answered this one too.
Create a visualtree off of a control template in code
The built in validation for WPF and Silverlight is meant for quick client-side validation (such as Regex, parsing values, etc.).
If you need to go to a server to perform validation (or validation takes a long time), I would do that in a custom way. Such as when clicking a save button, etc.
So say you have a Save method in a ViewModel (you don't mention which MVVM framework you use):
public void Save()
{
//Do your validation, this might start a new thread (I use Async CTP myself)
//If validation is good, do your extra work, else display validation errors
}
I would just do all the work required for this within an action in your ViewModel

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.

Event on validation - WPF

I'm looking at developing a simple validation framework for WPF (the IDataErrorInfo method doesn't provide enough info for my needs), and am wondering if there is a way to be notified when a Property is going to validate? Please note that I need to know any time it is going to attempt validation rather than only when there is an error (so NotifyOnValidationError doesn't cut it)
Alternatively, my ultimate goal is simply to package more information than just an error string into my validations (How critical is the error, links for more info, etc.) while still allowing the validation to be driven by the data object (IDataErrorInfo style). If anyone can point me to a method for doing that then I'll be perfectly happy as well. :)
The problem you are going to run into is that WPF databinding and validation are tied to the IDataErrorInfo interface. The bindings check for validation based on the UpdateSourceTrigger property of the binding. So if your binding has "UpdateSourceTrigger=PropertyChanged" then everytime the property changes it calls the item["MyProperty"] which is where you would return information as to whether of not your property is valid. If it's set to "LostFocus" then it checks whenever the control loses focus. The binding also requires the "ValidatesOnDataErrors=True" in order for it to force validation on your bound entity.
I think your best bet would be to create a class that implements IDataErrorInfo and then supply more detailed information based on the severity of the error.
You need to look into inheriting from ValidationRule and then adding the new rule to all you binding objects.

Resources